windows: the XRay-only backend; zapret beside the TUN

XRay alone (proxy.backend = "xray"), as upstream's xray.nix and its
start-time filter make it: the mixed-in listener with its login, DNS remote
and local ordered by the route mode with the servers' names on local,
IPIfNonMatch routing in upstream's order and modes, zapret's direct lists;
urltest as prefixed tags under a leastPing balancer and observatory, a pin
or first as one exit; chains by dialerProxy; Tor, SSH, WARP, AmneziaWG and
whitelist-bypass as SOCKS hops. What needs sing-box is refused for it, as
upstream asserts (TUN, groups, rule sets, autoProxy, selector/failover,
DoT, dns.strategy and the like). The service checks it with xray run -test
and runs it with its component's geodata (XRAY_LOCATION_ASSET); latency
tests and autoProxy stand aside.

zapret beside the TUN: winws2 gets the TUN's addresses left out in its
--wf-raw-filter (with the cutoff probe's ports); Flowseal's winws, which
takes no ANDed part, gets its own filter as it saves it (--wf-save) with
them left out, through --wf-raw. WinDivert negates single tests only: the
part is spelled positively, and compiled by WinDivert's own parser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-28 00:05:21 +03:00
1 parent 2dd563ed61
commit d675fdddb5
15 files changed
+831 -34

No files matched your search

@@ -41,6 +41,8 @@ fn main() {
exclude: format!("{state}zapret-hosts-user-exclude.txt"),
auto: format!("{state}learned\\zapret-hosts-auto.txt"),
extras,
// Beside sing-box's TUN, as its defaults are: checked by winws2 with the rest.
keep_off: ps_core::zapret::tun_exclusion("172.19.0.1/30", Some("fd66:19::1/64")),
};
for arg in args(&z, &source, &paths, false).unwrap() {
println!("{arg}");
+40 -6
View File
@@ -130,16 +130,10 @@ fn not_ported(cfg: &Config, v: &mut Issues) {
v.warn(path, format!("{what} {IGNORED}"));
}
}
if cfg.proxy.enable && cfg.proxy.backend == Backend::Xray {
v.warn("proxy.backend", "the xray backend is not on Windows yet: the proxy does not start with it (sing-box or hybrid do)");
}
let z = &cfg.zapret;
if z.enable && z.engine == ZapretEngine::DiscordYoutube && z.discord_youtube.include_extra_upstream_lists {
v.warn("zapret.zapret-discord-youtube.includeExtraUpstreamLists", "Flowseal's Windows release has no instagram, soundcloud or twitter list: ignored");
}
if z.enable && cfg.proxy.tun.enable {
v.warn("proxy.tun.enable", "TUN and zapret together: zapret's packets are not kept off the TUN on Windows yet; use one or the other");
}
}
fn proxy(cfg: &Config, v: &mut Issues) {
@@ -309,6 +303,9 @@ fn proxy(cfg: &Config, v: &mut Issues) {
if p.dns.fake_ip.enable && !sing_box {
v.error("proxy.dns.fakeIp.enable", "fake IP needs the sing-box or hybrid backend");
}
if p.enable && p.backend == Backend::Xray {
xray_backend(cfg, v);
}
if p.enable && !derived::has_available_outbounds(cfg) {
v.warn("proxy.outbounds", "the proxy has no outbound or subscription yet; it starts once one is added");
}
@@ -336,6 +333,43 @@ fn proxy(cfg: &Config, v: &mut Issues) {
}
}
/// What upstream asserts unavailable with `proxy.backend = "xray"`, and the transparent modes
/// this port has no XRay counterpart for. (Rule sets, groups, "failover", autoProxy, fake IP,
/// program rules, per-app routing and sing-box JSON are refused with the other backend checks.)
fn xray_backend(cfg: &Config, v: &mut Issues) {
const NEEDS: &str = "needs the sing-box or hybrid backend";
let p = &cfg.proxy;
if p.selection == Selection::Selector {
v.error("proxy.selection", format!("\"selector\" selection {NEEDS}"));
}
if p.dns.local.transport == super::DnsTransport::Tls || p.dns.remote.transport == super::DnsTransport::Tls {
v.error("proxy.dns", "DoT (type \"tls\") is not supported with the xray backend; use udp or tcp DNS");
}
if p.dns.strategy.is_some() {
v.error("proxy.dns.strategy", format!("dns.strategy {NEEDS}"));
}
if p.dns.client_subnet.is_some() {
v.error("proxy.dns.clientSubnet", format!("dns.clientSubnet {NEEDS}"));
}
if !p.dns.sing_box.servers.is_empty() || !p.dns.sing_box.rules.is_empty() {
v.error("proxy.dns.singBox", format!("dns.singBox.servers and rules {NEEDS}"));
}
if cfg.debug.connection_log.enable {
v.error("debug.connectionLog.enable", format!("the connection log {NEEDS}"));
}
if p.tun.enable {
v.error("proxy.tun.enable", "the TUN with the xray backend is not on Windows yet; use sing-box or hybrid for it");
}
if matches!(cfg.warp.as_outbound, Some(crate::config::WarpOutboundKind::SingBox)) && cfg.warp.enable {
v.error("warp.asOutbound", "a sing-box WARP endpoint needs the sing-box or hybrid backend; use \"userspace\"");
}
for (name, prof) in &cfg.amnezia_wg.profiles {
if cfg.amnezia_wg.enable && matches!(prof.as_outbound, Some(crate::config::AwgOutboundKind::SingBox)) {
v.error(format!("amneziaWg.profiles.{name}.asOutbound"), "a sing-box AmneziaWG endpoint needs the sing-box or hybrid backend; use \"userspace\"");
}
}
}
fn tunnels(cfg: &Config, v: &mut Issues) {
let proxy_on = cfg.proxy.enable;
+7 -3
View File
@@ -7,6 +7,9 @@ pub mod groups;
mod outbounds;
mod routing;
mod sing_box;
mod xray;
/// The TUN's IPv6 address (its IPv4 one is configured).
pub use sing_box::TUN_IPV6_ADDRESS;
use std::collections::{BTreeMap, HashMap};
use std::fmt;
@@ -160,9 +163,10 @@ pub fn render(input: &Input) -> Result<Rendered, RenderError> {
let (config, sidecar) = sing_box::config(input, &assembly, &probe_exits, &mut warnings)?;
Ok(Rendered { sing_box: Some(config), xray: sidecar, inventory: assembly.inventory, probe_exits, warnings })
}
crate::config::Backend::Xray => Err(RenderError(
"the \"xray\" backend is not rendered yet on Windows; use \"sing-box\" or \"hybrid\"".into(),
)),
crate::config::Backend::Xray => {
let config = xray::config(input, &assembly, &mut warnings)?;
Ok(Rendered { sing_box: None, xray: Some(config), inventory: assembly.inventory, probe_exits: Vec::new(), warnings })
}
}
}
+28 -6
View File
@@ -54,6 +54,8 @@ pub(super) struct Assembly {
/// The hybrid sidecar's XRay outbounds.
pub xray: Vec<Value>,
pub inventory: Inventory,
/// What selection may pick on its own (the XRay backend builds its "proxy" from it).
pub selectable: Vec<String>,
}
struct Builder<'a> {
@@ -136,6 +138,14 @@ impl Builder<'_> {
/// A loopback SOCKS hop to a helper the service runs.
fn hop(&self, tag: &str, port: u16, login: bool) -> Value {
if self.backend == Backend::Xray {
let mut ob = json!({ "protocol": "socks", "tag": tag, "settings": { "address": "127.0.0.1", "port": port } });
if let (true, Some((user, pass))) = (login, &self.input.env.hop_login) {
ob["settings"]["user"] = user.clone().into();
ob["settings"]["pass"] = pass.clone().into();
}
return ob;
}
let mut ob = json!({ "type": "socks", "tag": tag, "server": "127.0.0.1", "server_port": port });
if let (true, Some((user, pass))) = (login, &self.input.env.hop_login) {
ob["username"] = user.clone().into();
@@ -276,6 +286,10 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
}
ExtraKind::Warp { device } => match device.kind {
crate::config::WarpOutboundKind::SingBox => {
if p.backend == Backend::Xray {
warnings.push(format!("WARP device '{}': a sing-box endpoint needs the sing-box or hybrid backend (use \"userspace\"); leaving it out", device.tag));
continue;
}
let Some(profile) = input.env.warp_profiles.get(&device.tag) else {
warnings.push(format!("WARP device '{}' is not registered yet; it joins once it is", device.tag));
continue;
@@ -296,6 +310,10 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
},
ExtraKind::Awg { profile, kind, port } => match kind {
crate::config::AwgOutboundKind::SingBox => {
if p.backend == Backend::Xray {
warnings.push(format!("AmneziaWG outbound '{profile}': a sing-box endpoint needs the sing-box or hybrid backend (use \"userspace\"); leaving it out"));
continue;
}
let Some(conf) = input.env.awg_profiles.get(&profile) else {
warnings.push(format!("AmneziaWG outbound '{profile}': its config could not be read; leaving it out"));
continue;
@@ -341,7 +359,10 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
// Groups, against the outbounds this start has. A group whose name an outbound took, or
// that contains itself, is left out.
let mut group_cfg = p.groups.clone();
if let Some(warp) = warp_group(cfg) {
// Groups need sing-box (validated); the XRay backend has none, nor a "warp" group.
if p.backend == Backend::Xray {
group_cfg.clear();
} else if let Some(warp) = warp_group(cfg) {
group_cfg.entry(derived::WARP_TAG.into()).or_insert(warp);
}
group_cfg.retain(|name, _| {
@@ -424,11 +445,12 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
.cloned()
.collect();
// "proxy", as the selection mode has it, ahead of everything; the groups after the rest.
// "proxy", as the selection mode has it, ahead of everything; the groups after the rest. The
// XRay backend builds its own from `selectable` and the pin.
let mut every: Vec<String> = b.order.clone();
every.extend(resolved.groups.keys().cloned());
let default = if pinned.is_empty() { selectable[0].clone() } else { pinned.clone() };
let wrapper = match p.selection {
let wrapper = if p.backend == Backend::Xray { Value::Null } else { match p.selection {
Selection::First => json!({ "type": "selector", "tag": "proxy", "outbounds": [default], "default": default }),
Selection::Failover if pinned.is_empty() && !input.env.groups_watched => json!({
"type": "urltest", "tag": "proxy", "outbounds": selectable, "url": p.url_test.url,
@@ -446,8 +468,8 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
"type": "urltest", "tag": "proxy", "outbounds": selectable, "url": p.url_test.url,
"interval": p.url_test.interval, "tolerance": p.url_test.tolerance,
}),
};
let mut outbounds = vec![wrapper];
} };
let mut outbounds = if wrapper.is_null() { Vec::new() } else { vec![wrapper] };
outbounds.append(&mut b.outbounds);
outbounds.extend(resolved.outbounds.iter().cloned());
@@ -472,7 +494,7 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
.map(|t| (t.clone(), b.runs_on.get(t).cloned().unwrap_or_else(|| p.backend.as_str().to_owned())))
.collect(),
};
Ok(Assembly { outbounds, endpoints: b.endpoints, xray: b.xray, inventory })
Ok(Assembly { outbounds, endpoints: b.endpoints, xray: b.xray, inventory, selectable })
}
/// With two or more WARP devices, "warp" names a group of them.
@@ -52,7 +52,7 @@ fn hop_ports(input: &Input) -> Vec<u16> {
out
}
fn listener_users(input: &Input) -> Result<Option<Value>, RenderError> {
pub(super) fn listener_users(input: &Input) -> Result<Option<Value>, RenderError> {
let auth = &input.cfg.proxy.listener.auth;
let Some(user) = &auth.username else { return Ok(None) };
let password = match (&auth.password, &auth.password_file) {
+334
View File
@@ -0,0 +1,334 @@
//! The XRay-only backend's whole config: upstream's `config-templates/xray.nix` (its `tproxy`
//! variant, without TProxy), `rules/xray.nix` and the start-time `backend-filter-xray.template.jq`.
//! The transparent modes (TProxy, TUN, per-app TUN) have no counterpart here.
use std::collections::BTreeSet;
use serde_json::{Map, Value, json};
use super::outbounds::Assembly;
use super::routing::{LOOPBACK, direct_match};
use super::sing_box::{apply_xmux, listener_users, xray_log_level};
use super::{Input, RenderError, RouteMode};
use crate::config::{DnsTransport, DnsUpstream, RouteDefault, RouteMatch, Selection};
use crate::derived;
/// `urltest` renames every outbound so the balancer's selector can be a prefix.
const PREFIX: &str = "proxy-suite-ob-";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Category {
Proxy,
Direct,
Block,
/// Private addresses and the Telegram relay's: direct, but kept in every mode.
Safety,
}
fn category(target: &str) -> Category {
match target {
"direct" => Category::Direct,
"block" => Category::Block,
_ => Category::Proxy,
}
}
struct Section {
priority: i64,
category: Category,
rules: Vec<Value>,
}
/// Where a rule's outbound is in this config.
struct Targets {
prefixed: bool,
/// The one outbound "proxy" stands for (a pin, "first", or a balancer of one), renamed.
single: Option<String>,
}
impl Targets {
/// `{type, ruleTag, <fields>}` and its target: "proxy" is the balancer or the one exit.
fn rule(&self, rule_tag: &str, fields: Value, outbound: &str) -> Value {
let mut rule = json!({ "type": "field", "ruleTag": rule_tag });
if let Value::Object(f) = fields {
rule.as_object_mut().unwrap().extend(f);
}
match outbound {
"proxy" => match &self.single {
Some(tag) => rule["outboundTag"] = tag.clone().into(),
None => rule["balancerTag"] = "proxy".into(),
},
"direct" | "block" => rule["outboundTag"] = outbound.into(),
tag if self.prefixed => rule["outboundTag"] = format!("{PREFIX}{tag}").into(),
tag => rule["outboundTag"] = tag.into(),
}
rule
}
/// One rule per kind of match, as upstream's `mkXrayCustomRuleEntries` (a rule matches any
/// of them): `<prefix>-domain`, `-ip`, `-geosite`, `-geoip`.
fn match_rules(&self, rule_tag: &dyn Fn(&str) -> String, outbound: &str, m: &RouteMatch) -> Vec<Value> {
let mut rules = Vec::new();
if !m.domains.is_empty() {
let domains: Vec<String> = m.domains.iter().map(|d| format!("domain:{d}")).collect();
rules.push(self.rule(&rule_tag("domain"), json!({ "domain": domains }), outbound));
}
if !m.ips.is_empty() {
rules.push(self.rule(&rule_tag("ip"), json!({ "ip": m.ips }), outbound));
}
if !m.geosites.is_empty() {
let sites: Vec<String> = m.geosites.iter().map(|s| format!("geosite:{s}")).collect();
rules.push(self.rule(&rule_tag("geosite"), json!({ "domain": sites }), outbound));
}
if !m.geoips.is_empty() {
let ips: Vec<String> = m.geoips.iter().map(|s| format!("geoip:{s}")).collect();
rules.push(self.rule(&rule_tag("geoip"), json!({ "ip": ips }), outbound));
}
rules
}
}
fn dns_server(tag: &str, upstream: &DnsUpstream) -> Result<Value, RenderError> {
let address = match upstream.transport {
DnsTransport::Udp => upstream.address.clone(),
DnsTransport::Tcp => format!("tcp://{}", upstream.address),
DnsTransport::Tls => return Err(RenderError("proxy.dns.*.type = \"tls\" is not supported with the xray backend; use udp or tcp DNS".into())),
};
Ok(json!({ "address": address, "tag": tag, "port": upstream.port, "queryStrategy": "UseIP" }))
}
/// Names of proxy servers, which XRay's DNS resolves once a dial has a domainStrategy
/// (the jq's `xray_server_names`).
fn server_names(outbounds: &[Value]) -> BTreeSet<String> {
let mut names = BTreeSet::new();
for ob in outbounds {
let settings = &ob["settings"];
let addresses = settings["vnext"]
.as_array()
.into_iter()
.flatten()
.chain(settings["servers"].as_array().into_iter().flatten())
.map(|s| &s["address"])
.chain(std::iter::once(&settings["address"]));
for a in addresses.filter_map(Value::as_str) {
let numeric = a.chars().all(|c| c.is_ascii_digit() || c == '.');
if !numeric && !a.contains(':') && a != "localhost" {
names.insert(a.to_owned());
}
}
}
names
}
pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec<String>) -> Result<Value, RenderError> {
if input.tun {
return Err(RenderError("the TUN with the xray backend is not on Windows yet".into()));
}
let cfg = input.cfg;
let p = &cfg.proxy;
let r = &p.routing;
// "proxy": a balancer over every selectable outbound on urltest, else the one exit. XRay has
// no selector: a pin leaves the balancer with one outbound, which is the path "first" takes.
let urltest = p.selection == Selection::Urltest;
let pinned = &asm.inventory.pinned;
let single_raw = if !pinned.is_empty() {
Some(pinned.clone())
} else if urltest {
(asm.selectable.len() == 1).then(|| asm.selectable[0].clone())
} else {
asm.selectable.first().cloned()
};
let targets = Targets {
prefixed: urltest,
single: single_raw.map(|t| if urltest { format!("{PREFIX}{t}") } else { t }),
};
let balanced = urltest && targets.single.is_none();
// Outbounds: the exits, then the builtin ones.
let mut outbounds: Vec<Value> = Vec::new();
for ob in &asm.outbounds {
let mut ob = ob.clone();
apply_xmux(input, &mut ob);
if urltest {
let tag = ob["tag"].as_str().unwrap_or_default().to_owned();
ob["tag"] = format!("{PREFIX}{tag}").into();
if let Some(hop) = ob.pointer("/streamSettings/sockopt/dialerProxy").and_then(Value::as_str) {
ob["streamSettings"]["sockopt"]["dialerProxy"] = format!("{PREFIX}{hop}").into();
}
}
outbounds.push(ob);
}
let names = server_names(&outbounds);
// No loopback by any name for what goes direct, besides the resolvers on it: the loopback
// hops, the helpers' listeners and whatever else listens there are nothing to dial.
let loopback_dns_ports: BTreeSet<u16> = [&p.dns.local, &p.dns.remote]
.into_iter()
.filter(|u| u.address.starts_with("127.") || u.address == "::1" || u.address == "localhost")
.map(|u| u.port)
.collect();
let mut final_rules = Vec::new();
if !loopback_dns_ports.is_empty() {
let ports: Vec<String> = loopback_dns_ports.iter().map(u16::to_string).collect();
final_rules.push(json!({ "action": "allow", "ip": LOOPBACK, "port": ports.join(",") }));
}
final_rules.push(json!({ "action": "block", "ip": LOOPBACK, "blockDelay": 0 }));
outbounds.push(json!({ "protocol": "freedom", "tag": "direct", "settings": { "finalRules": final_rules } }));
outbounds.push(json!({ "protocol": "blackhole", "tag": "block", "settings": {} }));
// No rule takes packets to dns-out here (those are TProxy's and the TUN's), but it is the
// template's: .onion is told there is no such name, other record types go on.
let mut dns_rules = Vec::new();
if derived::tor_route_onion(cfg) {
dns_rules.push(json!({ "action": "return", "rCode": 3, "domain": ["domain:onion"] }));
}
dns_rules.push(json!({ "action": "direct", "qType": "2-27,29-65535" }));
outbounds.push(json!({ "protocol": "dns", "tag": "dns-out", "settings": { "userLevel": 0, "rules": dns_rules } }));
// The mode: the configured default, or proxy-ctl's override.
let mode = input.state.route_mode.unwrap_or(match r.default {
RouteDefault::Proxy => RouteMode::Blacklist,
RouteDefault::Direct => RouteMode::Whitelist,
});
let (final_outbound, remote_first) = match mode {
RouteMode::Blacklist | RouteMode::AllProxy => ("proxy", true),
RouteMode::Whitelist | RouteMode::AllBypass => ("direct", false),
};
// DNS: the preferred server first (the backend filter's `xray_dns_server_order`), proxy
// servers' names pinned to a copy of "local".
let remote = dns_server("remote", &p.dns.remote)?;
let local = dns_server("local", &p.dns.local)?;
let mut servers = if remote_first { vec![remote, local.clone()] } else { vec![local.clone(), remote] };
if !names.is_empty() {
let mut pinned_local = local;
pinned_local["domains"] = names.iter().map(|n| format!("full:{n}")).collect::<Vec<_>>().into();
pinned_local["skipFallback"] = true.into();
servers.push(pinned_local);
}
// Rules. What XRay's DNS asks for goes by the server's tag: "local" direct, "remote" through
// the proxy.
let mut rules = vec![
targets.rule("dns-upstream-direct", json!({ "inboundTag": ["local"], "network": "tcp,udp" }), "direct"),
targets.rule("dns-upstream-remote", json!({ "inboundTag": ["remote"], "network": "tcp,udp" }), "proxy"),
];
// Nothing reaches this host's loopback through the proxy, by address or by name. Upstream
// guards the transparent inbounds only (its firewall keeps the rest from other users);
// Windows has no such firewall here, so the local listener too.
let onion = derived::tor_route_onion(cfg) && asm.inventory.tags.iter().any(|t| t == derived::TOR_OUTBOUND_TAG);
let mut common = vec![
targets.rule("guard-loopback-ip", json!({ "inboundTag": ["mixed-in"], "ip": LOOPBACK }), "block"),
targets.rule("guard-loopback-domain", json!({ "inboundTag": ["mixed-in"], "domain": ["domain:localhost"] }), "block"),
];
if onion {
common.push(targets.rule("tor-onion", json!({ "domain": ["domain:onion"] }), derived::TOR_OUTBOUND_TAG));
}
rules.extend(common);
let known = |t: &str| asm.inventory.tags.iter().any(|x| x == t);
let mut sections = Vec::new();
let custom_tag = |outbound: &str| {
let c = match category(outbound) {
Category::Direct => "direct",
Category::Block => "block",
_ => "proxy",
};
let c = c.to_owned();
move |kind: &str| format!("custom-{c}-{kind}")
};
for ob in &p.outbounds {
if ob.routing.is_empty() {
continue;
}
let outbound = if known(&ob.tag) {
ob.tag.as_str()
} else {
warnings.push(format!("outbound '{}' is not running: what its routing sends to it is blocked until it is", ob.tag));
"block"
};
let tag = custom_tag(outbound);
sections.push(Section { priority: 100, category: category(outbound), rules: targets.match_rules(&tag, outbound, &ob.routing) });
}
for (i, rule) in r.rules.iter().enumerate() {
if rule.disabled {
continue;
}
let name = rule.name.clone().unwrap_or_else(|| format!("#{i}"));
let outbound = if derived::BUILTIN_TAGS.contains(&rule.outbound.as_str()) || known(&rule.outbound) {
rule.outbound.as_str()
} else {
warnings.push(format!("routing rule {name}: no outbound named '{}' is running; what it matches is blocked until it is", rule.outbound));
"block"
};
let tag = custom_tag(outbound);
sections.push(Section {
priority: rule.priority.unwrap_or(100),
category: category(outbound),
rules: targets.match_rules(&tag, outbound, &rule.matches),
});
}
let direct = direct_match(input);
let fixed = |prefix: &'static str| move |kind: &str| format!("{prefix}-{kind}");
let proxy_primary = RouteMatch { domains: r.proxy.domains.clone(), ips: r.proxy.ips.clone(), ..Default::default() };
let proxy_geo = RouteMatch { geosites: r.proxy.geosites.clone(), geoips: r.proxy.geoips.clone(), ..Default::default() };
sections.push(Section { priority: 200, category: Category::Proxy, rules: targets.match_rules(&fixed("proxy"), "proxy", &proxy_primary) });
// Block ahead of the direct lists (category-ru's ad domains are in category-ads-all too).
sections.push(Section { priority: 300, category: Category::Block, rules: targets.match_rules(&fixed("block"), "block", &r.block) });
sections.push(Section { priority: 400, category: Category::Direct, rules: targets.match_rules(&fixed("direct"), "direct", &direct) });
let mut safety = vec![targets.rule("direct-private", json!({ "ip": ["geoip:private"] }), "direct")];
let tg = &cfg.tg_ws_proxy;
if tg.enable && tg.bypass_transparent_proxy && !tg.dc_ips.is_empty() {
let ips: BTreeSet<&String> = tg.dc_ips.values().collect();
safety.push(targets.rule("direct-tg-relay", json!({ "ip": ips }), "direct"));
}
sections.push(Section { priority: 400, category: Category::Safety, rules: safety });
// Geosite and geoip lists last: they are the heaviest to match.
sections.push(Section { priority: 500, category: Category::Proxy, rules: targets.match_rules(&fixed("proxy"), "proxy", &proxy_geo) });
let keep = |c: Category| match mode {
RouteMode::AllProxy => c != Category::Direct,
RouteMode::AllBypass => matches!(c, Category::Block | Category::Safety),
_ => true,
};
// A stable sort: among equals, the list's own order.
sections.sort_by_key(|s| s.priority);
rules.extend(sections.into_iter().filter(|s| keep(s.category)).flat_map(|s| s.rules));
rules.push(targets.rule("final-default", json!({ "network": "tcp,udp" }), final_outbound));
let mut routing = json!({ "domainStrategy": "IPIfNonMatch", "domainMatcher": "hybrid", "rules": rules });
let mut config = Map::new();
if balanced {
// Only what selection may pick: not proxy.selectionExclude, nor what is disabled.
let candidates: Vec<String> = asm.selectable.iter().map(|t| format!("{PREFIX}{t}")).collect();
routing["balancers"] = json!([{ "tag": "proxy", "selector": candidates, "strategy": { "type": "leastPing" } }]);
config.insert(
"observatory".into(),
json!({ "subjectSelector": candidates, "probeUrl": p.url_test.url, "probeInterval": p.url_test.interval }),
);
}
// The listener: sniffing puts a name in place of the address a client connected to, so the
// domain rules see it.
let mut settings = json!({ "auth": "noauth", "udp": true, "ip": p.listener.address });
if let Some(users) = listener_users(input)? {
let accounts: Vec<Value> =
users.as_array().into_iter().flatten().map(|u| json!({ "user": u["username"], "pass": u["password"] })).collect();
settings["auth"] = "password".into();
settings["accounts"] = accounts.into();
}
let mixed = json!({
"tag": "mixed-in", "protocol": "socks", "listen": p.listener.address, "port": p.listener.port,
"settings": settings,
"sniffing": { "enabled": true, "destOverride": ["http", "tls", "quic"] },
});
config.insert("log".into(), json!({ "loglevel": xray_log_level(input), "access": "none" }));
config.insert("dns".into(), json!({ "queryStrategy": "UseIP", "servers": servers }));
config.insert("inbounds".into(), json!([mixed]));
config.insert("outbounds".into(), Value::Array(outbounds));
config.insert("routing".into(), routing);
Ok(Value::Object(config))
}
+62
View File
@@ -497,6 +497,68 @@ pub fn direct_sync(z: &Zapret, list_general: &str, list_google: &str, list_exclu
(dedup(domains), dedup(ips))
}
// --- zapret beside the TUN ---------------------------------------------------------------
/// A WinDivert filter part that leaves out the packets of sing-box's TUN: what the apps send
/// into it carries its address as the source, what sing-box hands back as the destination.
/// zapret changing them would break them before sing-box reads them; it still sees the
/// connections sing-box makes (direct ones included) on the way out of the real adapter.
/// `v4`, `v6`: the TUN's addresses (CIDR); None for an address that does not read.
pub fn tun_exclusion(v4: &str, v6: Option<&str>) -> Option<String> {
use std::net::{Ipv4Addr, Ipv6Addr};
// WinDivert negates a single test only, never a group: each "not from or to the TUN" is
// spelled out (a packet is inbound when it is not outbound).
let mut parts = Vec::new();
let (ip, len) = v4.split_once('/')?;
let (ip, len): (Ipv4Addr, u32) = (ip.parse().ok()?, len.parse().ok().filter(|l| *l <= 32)?);
let mask = if len == 0 { 0 } else { u32::MAX << (32 - len) };
let (lo, hi) = (Ipv4Addr::from(u32::from(ip) & mask), Ipv4Addr::from(u32::from(ip) | !mask));
parts.push(format!("(not ip or inbound or ip.SrcAddr < {lo} or ip.SrcAddr > {hi})"));
parts.push(format!("(not ip or outbound or ip.DstAddr < {lo} or ip.DstAddr > {hi})"));
if let Some(v6) = v6 {
let (ip, len) = v6.split_once('/')?;
let (ip, len): (Ipv6Addr, u32) = (ip.parse().ok()?, len.parse().ok().filter(|l| *l <= 128)?);
let mask = if len == 0 { 0 } else { u128::MAX << (128 - len) };
let (lo, hi) = (Ipv6Addr::from(u128::from(ip) & mask), Ipv6Addr::from(u128::from(ip) | !mask));
parts.push(format!("(not ipv6 or inbound or ipv6.SrcAddr < {lo} or ipv6.SrcAddr > {hi})"));
parts.push(format!("(not ipv6 or outbound or ipv6.DstAddr < {lo} or ipv6.DstAddr > {hi})"));
}
Some(parts.join(" and "))
}
/// winws's arguments with its whole filter given instead (`--wf-raw=@file`, which replaces
/// the port options and the filter parts): for Flowseal's winws, which takes no part ANDed
/// with the rest. `file` holds what `--wf-save` printed for `argv`, with what is ANDed to it.
pub fn with_raw_filter(argv: &[String], file: &str) -> Vec<String> {
let mut out: Vec<String> = argv.iter().filter(|a| !["--wf-tcp=", "--wf-udp=", "--wf-raw-part=", "--wf-raw="].iter().any(|p| a.starts_with(p))).cloned().collect();
// The filter options go before the profiles (`--new`), as the presets give them.
let at = out.iter().position(|a| a == "--new" || !a.starts_with("--wf-") && !a.starts_with("--debug")).unwrap_or(out.len());
out.insert(at, format!("--wf-raw=@{file}"));
out
}
#[cfg(test)]
mod tun_tests {
use super::*;
#[test]
fn the_tuns_packets_are_left_out() {
let f = tun_exclusion("172.19.0.1/30", Some("fd66:19::1/64")).unwrap();
assert!(f.starts_with("(not ip or inbound or ip.SrcAddr < 172.19.0.0 or ip.SrcAddr > 172.19.0.3) and "), "{f}");
assert!(f.ends_with("(not ipv6 or outbound or ipv6.DstAddr < fd66:19:: or ipv6.DstAddr > fd66:19::ffff:ffff:ffff:ffff)"), "{f}");
assert!(!f.contains("not ("), "WinDivert negates no group: {f}");
assert_eq!(tun_exclusion("172.19.0.1", None), None);
assert!(!tun_exclusion("10.0.0.1/8", None).unwrap().contains("ipv6"));
}
#[test]
fn a_raw_filter_replaces_the_ports_and_parts() {
let argv: Vec<String> = ["--debug=1", "--wf-tcp=80,443", "--wf-udp=443", "--wf-raw-part=x", "--filter-tcp=80", "--dpi-desync=fake", "--new", "--filter-udp=443"].map(String::from).to_vec();
assert_eq!(with_raw_filter(&argv, "C:\\f.txt"), ["--debug=1", "--wf-raw=@C:\\f.txt", "--filter-tcp=80", "--dpi-desync=fake", "--new", "--filter-udp=443"]);
}
}
#[cfg(test)]
mod tests {
use super::*;
+8 -2
View File
@@ -158,6 +158,9 @@ pub struct Paths {
pub auto: String,
/// The zapret2-extras component, when installed: upstream's Lua layers and z2k's.
pub extras: Option<Extras>,
/// A WinDivert filter part ANDed with the rest, besides the cutoff probe's: the TUN's
/// packets left out (ps_core::zapret::tun_exclusion).
pub keep_off: Option<String>,
}
/// Where the zapret2-extras component's files are, as winws2 reads them.
@@ -516,8 +519,10 @@ pub fn args(z: &Zapret2, source: &Source, p: &Paths, debug_packets: bool) -> Res
}
// The cutoff probe measures the line itself: its connections pass winws2 untouched. (One
// such filter only: a profile's own goes first.)
if z.cutoff.enable && !body.iter().any(|a| a.starts_with("--wf-raw-filter")) {
opt.push(format!("--wf-raw-filter={}", cutoff_filter()));
let ands: Vec<String> = z.cutoff.enable.then(cutoff_filter).into_iter().chain(p.keep_off.clone()).collect();
if !ands.is_empty() && !body.iter().any(|a| a.starts_with("--wf-raw-filter")) {
let all = if ands.len() == 1 { ands[0].clone() } else { ands.iter().map(|a| format!("({a})")).collect::<Vec<_>>().join(" and ") };
opt.push(format!("--wf-raw-filter={all}"));
}
opt.extend(body);
Ok(opt)
@@ -763,6 +768,7 @@ UDP_PORTS=443,590:600
exclude: r"C:\s\exclude.txt".into(),
auto: r"C:\s\learned\auto.txt".into(),
extras: None,
keep_off: None,
}
}
+285
View File
@@ -336,3 +336,288 @@ fn helper_programs_go_direct_only_from_the_tun() {
assert_eq!(under_tun.len(), 1);
assert_eq!(under_tun[0]["inbound"], json!(["tun-in"]));
}
/// The xray backend's config, rendered and checked by `xray run -test`.
fn render_xray(cfg: &Config, state: &State, dir: &Path) -> (Value, Vec<String>) {
let mut cfg = cfg.clone();
cfg.proxy.backend = Backend::Xray;
let r = render(&Input { cfg: &cfg, state, subscriptions: &BTreeMap::new(), env: &env(dir), read_file: &no_files, tun: false }).unwrap();
assert!(r.sing_box.is_none() && r.probe_exits.is_empty());
let x = r.xray.unwrap();
check_xray(&x, dir);
(x, r.warnings)
}
fn xray_rules(x: &Value) -> &Vec<Value> {
x["routing"]["rules"].as_array().unwrap()
}
fn xray_rule<'a>(x: &'a Value, tag: &str) -> Option<&'a Value> {
xray_rules(x).iter().find(|r| r["ruleTag"] == tag)
}
fn xray_tags(x: &Value) -> Vec<&str> {
x["outbounds"].as_array().unwrap().iter().map(|o| o["tag"].as_str().unwrap()).collect()
}
fn xray_dns_tags(x: &Value) -> Vec<&str> {
x["dns"]["servers"].as_array().unwrap().iter().map(|s| s["tag"].as_str().unwrap()).collect()
}
fn xray_base() -> Config {
let mut cfg = base();
cfg.proxy.outbounds[0] = outbound("nl", "trojan://pw@nl.example.com:443?sni=nl.example.com");
cfg
}
#[test]
fn xray_route_modes_change_the_final_the_lists_and_the_dns_order() {
let dir = scratch("xray-modes");
let mut cfg = xray_base();
cfg.proxy.routing.direct.domains = vec!["direct.example".into()];
cfg.proxy.routing.direct.geoips = vec!["cn".into()];
cfg.proxy.routing.block.domains = vec!["ads.example".into()];
cfg.proxy.routing.proxy.domains = vec!["proxy.example".into()];
cfg.proxy.routing.proxy.geosites = vec!["netflix".into()];
for (mode, final_ob, has_direct, remote_first) in [
(None, "nl", true, true),
(Some(RouteMode::Whitelist), "direct", true, false),
(Some(RouteMode::AllProxy), "nl", false, true),
(Some(RouteMode::AllBypass), "direct", false, false),
] {
let state = State { route_mode: mode, ..Default::default() };
let (x, _) = render_xray(&cfg, &state, &dir);
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], final_ob, "{mode:?}");
assert_eq!(xray_rule(&x, "direct-domain").is_some(), has_direct, "{mode:?}");
assert_eq!(xray_rule(&x, "direct-geoip").is_some(), has_direct, "{mode:?}");
// Block and the private-address safety stay in every mode.
assert_eq!(xray_rule(&x, "block-domain").unwrap()["outboundTag"], "block", "{mode:?}");
assert!(xray_rule(&x, "direct-private").is_some(), "{mode:?}");
let proxied = mode != Some(RouteMode::AllBypass);
assert_eq!(xray_rule(&x, "proxy-domain").is_some(), proxied, "{mode:?}");
assert_eq!(xray_rule(&x, "proxy-geosite").is_some(), proxied, "{mode:?}");
// The DNS server the mode prefers comes first.
assert_eq!(xray_dns_tags(&x)[0], if remote_first { "remote" } else { "local" }, "{mode:?}");
}
// The order of the lists: block ahead of direct, the geo lists of the proxy last.
let (x, _) = render_xray(&cfg, &State::default(), &dir);
let pos = |tag: &str| xray_rules(&x).iter().position(|r| r["ruleTag"] == tag).unwrap();
assert!(pos("proxy-domain") < pos("block-domain") && pos("block-domain") < pos("direct-domain"));
assert!(pos("direct-private") < pos("proxy-geosite") && pos("proxy-geosite") < pos("final-default"));
assert_eq!(xray_rule(&x, "proxy-geosite").unwrap()["domain"], json!(["geosite:netflix"]));
assert_eq!(xray_rule(&x, "direct-domain").unwrap()["domain"], json!(["domain:direct.example"]));
assert_eq!(x["routing"]["domainStrategy"], "IPIfNonMatch");
assert_eq!(x["routing"]["domainMatcher"], "hybrid");
}
#[test]
fn xray_dns_follows_routing_default_and_pins_the_proxy_servers() {
let dir = scratch("xray-dns");
let mut cfg = xray_base();
cfg.proxy.dns.remote = DnsUpstream { transport: DnsTransport::Tcp, address: "9.9.9.9".into(), port: 5353 };
let (x, _) = render_xray(&cfg, &State::default(), &dir);
// proxy: remote first; the copy of "local" that answers for the servers' names last.
assert_eq!(xray_dns_tags(&x), ["remote", "local", "local"]);
let servers = x["dns"]["servers"].as_array().unwrap();
assert_eq!(servers[0]["address"], "tcp://9.9.9.9");
assert_eq!(servers[0]["port"], 5353);
assert_eq!(servers[2]["domains"], json!(["full:de.example.com", "full:nl.example.com"]));
assert_eq!(servers[2]["skipFallback"], true);
assert!(servers[1].get("domains").is_none());
// The server's own queries: local direct, remote through the proxy.
assert_eq!(xray_rule(&x, "dns-upstream-direct").unwrap()["outboundTag"], "direct");
assert_eq!(xray_rule(&x, "dns-upstream-remote").unwrap()["outboundTag"], "nl");
cfg.proxy.routing.default = RouteDefault::Direct;
let (x, _) = render_xray(&cfg, &State::default(), &dir);
assert_eq!(xray_dns_tags(&x), ["local", "remote", "local"]);
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], "direct");
// DoT has no XRay counterpart.
cfg.proxy.backend = Backend::Xray;
cfg.proxy.dns.local.transport = DnsTransport::Tls;
let err = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &env(&dir), read_file: &no_files, tun: false }).unwrap_err();
assert!(err.0.contains("tls"), "{err}");
}
#[test]
fn xray_urltest_balances_and_a_pin_leaves_one_exit() {
let dir = scratch("xray-urltest");
let mut cfg = xray_base();
cfg.proxy.selection = Selection::Urltest;
cfg.proxy.url_test.url = "https://probe.example/204".into();
cfg.proxy.url_test.interval = "90s".into();
cfg.proxy.outbounds.push(outbound("ru", "trojan://pw@ru.example.com:443?sni=ru.example.com"));
cfg.proxy.outbounds[2].routing.domains = vec!["ru.example".into()];
cfg.proxy.selection_exclude = vec!["ru".into()];
cfg.proxy.routing.proxy.domains = vec!["proxy.example".into()];
let (x, _) = render_xray(&cfg, &State::default(), &dir);
assert_eq!(xray_tags(&x)[..3], ["proxy-suite-ob-nl", "proxy-suite-ob-de", "proxy-suite-ob-ru"]);
// The balancer takes what selection may pick, not the excluded outbound.
let candidates = json!(["proxy-suite-ob-nl", "proxy-suite-ob-de"]);
assert_eq!(x["routing"]["balancers"], json!([{ "tag": "proxy", "selector": candidates, "strategy": { "type": "leastPing" } }]));
assert_eq!(x["observatory"], json!({ "subjectSelector": candidates, "probeUrl": "https://probe.example/204", "probeInterval": "90s" }));
assert_eq!(xray_rule(&x, "final-default").unwrap()["balancerTag"], "proxy");
assert_eq!(xray_rule(&x, "proxy-domain").unwrap()["balancerTag"], "proxy");
assert_eq!(xray_rule(&x, "dns-upstream-remote").unwrap()["balancerTag"], "proxy");
// An outbound's own routing names it, renamed with the rest.
assert_eq!(xray_rule(&x, "custom-proxy-domain").unwrap()["outboundTag"], "proxy-suite-ob-ru");
// A pin: no balancer, no observatory, every "proxy" rule on the one exit.
let state = State { pin: Some("de".into()), ..Default::default() };
let (x, _) = render_xray(&cfg, &state, &dir);
assert!(x["routing"].get("balancers").is_none() && x.get("observatory").is_none());
for tag in ["final-default", "proxy-domain", "dns-upstream-remote"] {
let r = xray_rule(&x, tag).unwrap();
assert_eq!(r["outboundTag"], "proxy-suite-ob-de", "{tag}");
assert!(r.get("balancerTag").is_none(), "{tag}");
}
assert_eq!(xray_rule(&x, "custom-proxy-domain").unwrap()["outboundTag"], "proxy-suite-ob-ru");
// One selectable outbound is a pin of its own.
cfg.proxy.selection_exclude = vec!["ru".into(), "de".into()];
let (x, _) = render_xray(&cfg, &State::default(), &dir);
assert!(x["routing"].get("balancers").is_none() && x.get("observatory").is_none());
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], "proxy-suite-ob-nl");
}
#[test]
fn xray_first_selection_takes_the_first_outbound_or_the_pin() {
let dir = scratch("xray-first");
let cfg = xray_base();
let (x, _) = render_xray(&cfg, &State::default(), &dir);
assert_eq!(xray_tags(&x), ["nl", "de", "direct", "block", "dns-out"]);
assert!(x["routing"].get("balancers").is_none() && x.get("observatory").is_none());
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], "nl");
let state = State { pin: Some("de".into()), ..Default::default() };
let (x, _) = render_xray(&cfg, &state, &dir);
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], "de");
// Every tag stays, so a rule naming another outbound still reaches it.
let mut cfg = cfg;
cfg.proxy.routing.rules.push(RoutingRule { outbound: "nl".into(), matches: RouteMatch { ips: vec!["203.0.113.0/24".into()], geoips: vec!["us".into()], ..Default::default() }, ..Default::default() });
cfg.proxy.routing.rules.push(RoutingRule { outbound: "direct".into(), matches: RouteMatch { domains: vec!["lan.example".into()], ..Default::default() }, ..Default::default() });
let (x, _) = render_xray(&cfg, &state, &dir);
assert_eq!(xray_rule(&x, "custom-proxy-ip").unwrap()["outboundTag"], "nl");
assert_eq!(xray_rule(&x, "custom-proxy-geoip").unwrap()["ip"], json!(["geoip:us"]));
assert_eq!(xray_rule(&x, "custom-direct-domain").unwrap()["outboundTag"], "direct");
}
#[test]
fn xray_listener_takes_a_login_and_guards_loopback() {
let dir = scratch("xray-listener");
let mut cfg = xray_base();
let (x, _) = render_xray(&cfg, &State::default(), &dir);
let inbound = &x["inbounds"][0];
assert_eq!(inbound["tag"], "mixed-in");
assert_eq!(inbound["protocol"], "socks");
assert_eq!(inbound["listen"], "127.0.0.1");
assert_eq!(inbound["port"], 1080);
assert_eq!(inbound["settings"]["auth"], "noauth");
assert_eq!(inbound["settings"]["udp"], true);
assert_eq!(x["inbounds"].as_array().unwrap().len(), 1);
cfg.proxy.listener.auth = ListenerAuth { username: Some("me".into()), password: Some("pw".into()), password_file: None };
let (x, _) = render_xray(&cfg, &State::default(), &dir);
assert_eq!(x["inbounds"][0]["settings"]["auth"], "password");
assert_eq!(x["inbounds"][0]["settings"]["accounts"], json!([{ "user": "me", "pass": "pw" }]));
// Nothing reaches this host's loopback: by address or name through the listener, or from a
// name the direct outbound resolves.
assert_eq!(xray_rule(&x, "guard-loopback-ip").unwrap()["outboundTag"], "block");
assert_eq!(xray_rule(&x, "guard-loopback-domain").unwrap()["domain"], json!(["domain:localhost"]));
let direct = x["outbounds"].as_array().unwrap().iter().find(|o| o["tag"] == "direct").unwrap();
assert_eq!(direct["settings"]["finalRules"].as_array().unwrap().last().unwrap()["action"], "block");
}
#[test]
fn xray_chains_and_helpers_are_xray_outbounds() {
let dir = scratch("xray-chain");
let mut cfg = xray_base();
cfg.proxy.outbounds.push(Outbound { detour: Some("nl".into()), ..outbound("chained", "trojan://pw@t.example.com:443?sni=t.example.com") });
cfg.proxy.outbounds.push(Outbound { tag: "raw".into(), xray_json: Some(serde_json::from_value(json!({ "protocol": "freedom", "settings": {} })).unwrap()), ..Default::default() });
cfg.tor.enable = true;
cfg.tor.as_outbound = true;
cfg.warp.enable = true;
cfg.warp.as_outbound = Some(WarpOutboundKind::Userspace);
cfg.ssh_proxy.enable = true;
cfg.ssh_proxy.as_outbound = true;
cfg.ssh_proxy.server = SshServer { user: Some("root".into()), host: Some("ssh.example.com".into()), port: 22 };
cfg.whitelist_bypass.enable = true;
cfg.whitelist_bypass.joiners.insert("wl".into(), WlJoiner { platform: WlPlatform::Wbstream, link_file: None });
cfg.proxy.routing.rules.push(RoutingRule { outbound: "gone".into(), matches: RouteMatch { domains: vec!["x.example".into()], ..Default::default() }, ..Default::default() });
for urltest in [false, true] {
cfg.proxy.selection = if urltest { Selection::Urltest } else { Selection::First };
let (x, warnings) = render_xray(&cfg, &State::default(), &dir);
let prefix = if urltest { "proxy-suite-ob-" } else { "" };
let ob = |tag: &str| x["outbounds"].as_array().unwrap().iter().find(|o| o["tag"] == format!("{prefix}{tag}")).unwrap_or_else(|| panic!("no {tag}: {:?}", xray_tags(&x)));
assert_eq!(ob("chained")["streamSettings"]["sockopt"]["dialerProxy"], format!("{prefix}nl"));
// The helpers' loopback SOCKS listeners, with the hop login where the service set one.
let tor = ob("tor");
assert_eq!(tor["protocol"], "socks");
assert_eq!(tor["settings"]["address"], "127.0.0.1");
assert!(tor["settings"].get("user").is_none());
assert!(ob("ssh-proxy")["settings"].get("user").is_none());
assert_eq!(ob("warp")["settings"]["user"], "hop");
assert_eq!(ob("warp")["settings"]["pass"], "hop-pass");
assert_eq!(ob("wl")["settings"]["user"], "hop");
assert_eq!(ob("raw")["protocol"], "freedom");
// Tor is for what is routed to it: not selected on its own.
assert_eq!(xray_rule(&x, "final-default").unwrap().get("balancerTag").is_some(), urltest);
if urltest {
let selector = x["routing"]["balancers"][0]["selector"].as_array().unwrap();
assert!(!selector.contains(&json!("proxy-suite-ob-tor")), "{selector:?}");
}
assert_eq!(xray_rule(&x, "tor-onion").unwrap()["outboundTag"], format!("{prefix}tor"));
assert_eq!(xray_rule(&x, "custom-block-domain").unwrap()["outboundTag"], "block");
assert!(warnings.iter().any(|w| w.contains("'gone'")), "{warnings:?}");
}
// Endpoints are sing-box's: left out, with a word.
cfg.warp.as_outbound = Some(WarpOutboundKind::SingBox);
let (x, warnings) = render_xray(&cfg, &State::default(), &dir);
assert!(!xray_tags(&x).contains(&"warp"));
assert!(warnings.iter().any(|w| w.contains("WARP")), "{warnings:?}");
}
#[test]
fn xray_zapret_direct_lists_go_direct() {
let dir = scratch("xray-zapret");
let cfg = xray_base();
let mut e = env(&dir);
e.zapret_direct = RouteMatch { domains: vec!["blocked.example".into()], ips: vec!["198.51.100.0/24".into()], ..Default::default() };
// zapret2's runtime rule-sets are sing-box's: pure XRay has no equivalent.
e.zapret2_direct_rule_set = Some("zapret.json".into());
let mut cfg = cfg;
cfg.proxy.backend = Backend::Xray;
let r = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun: false }).unwrap();
let x = r.xray.unwrap();
check_xray(&x, &dir);
let domains = xray_rule(&x, "direct-domain").unwrap();
assert_eq!(domains["outboundTag"], "direct");
assert!(domains["domain"].as_array().unwrap().contains(&json!("domain:blocked.example")));
assert!(xray_rule(&x, "direct-ip").unwrap()["ip"].as_array().unwrap().contains(&json!("198.51.100.0/24")));
assert!(!x.to_string().contains("zapret.json"));
}
#[test]
fn xray_backend_refuses_what_it_cannot_do() {
let mut cfg = xray_base();
cfg.proxy.backend = Backend::Xray;
let refused = |cfg: &Config| -> Vec<String> {
ps_core::config::validate(cfg).into_iter().filter(|i| i.severity == Severity::Error).map(|i| i.path).collect()
};
assert!(refused(&cfg).is_empty(), "{:?}", refused(&cfg));
let mut c = cfg.clone();
c.proxy.selection = Selection::Selector;
assert!(refused(&c).contains(&"proxy.selection".to_owned()));
let mut c = cfg.clone();
c.proxy.tun.enable = true;
assert!(refused(&c).contains(&"proxy.tun.enable".to_owned()));
let mut c = cfg.clone();
c.proxy.dns.remote.transport = DnsTransport::Tls;
assert!(refused(&c).contains(&"proxy.dns".to_owned()));
let mut c = cfg.clone();
c.proxy.dns.strategy = Some(DomainStrategy::Ipv4Only);
assert!(refused(&c).contains(&"proxy.dns.strategy".to_owned()));
let mut c = cfg.clone();
c.debug.connection_log.enable = true;
assert!(refused(&c).contains(&"debug.connectionLog.enable".to_owned()));
// The TUN is refused at render too, whatever the validation was told.
let r = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &env(&scratch("xray-tun")), read_file: &no_files, tun: true });
assert!(r.unwrap_err().0.contains("TUN"));
}
+3
View File
@@ -437,6 +437,9 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
}
Request::Test { tags } => {
if shared.lock().await.cfg().proxy.backend == ps_core::config::Backend::Xray {
return Response::err("latency tests need the sing-box or hybrid backend");
}
let (clash, tags, url) = {
let s = shared.lock().await;
let Some(r) = &s.last else { return Response::err("the proxy is not running") };
+2 -1
View File
@@ -251,7 +251,8 @@ async fn get_text(port: u16, login: &(String, String), url: &str) -> Option<Stri
/// The probe listeners, when autoProxy runs with the local proxy.
pub fn exits(s: &crate::service::Service) -> Option<Exits> {
let cfg = s.cfg();
if !(cfg.enable && cfg.proxy.enable && cfg.proxy.auto_proxy.enable) || s.sup.state_of(SOCKS_UNIT) != UnitState::Active {
// No Clash API on the xray backend (validated away too).
if !(cfg.enable && cfg.proxy.enable && cfg.proxy.auto_proxy.enable) || cfg.proxy.backend == ps_core::config::Backend::Xray || s.sup.state_of(SOCKS_UNIT) != UnitState::Active {
return None;
}
let list = s.last.as_ref()?.probe_exits.clone();
+20 -8
View File
@@ -418,14 +418,26 @@ impl Service {
// last good one running.
let candidate = run.join("candidate.json");
write_atomic(&candidate, &main_json)?;
if backend != Backend::Xray {
let out = tokio::process::Command::new(&main_program).args(["check", "-c"]).arg(&candidate).output().await?;
if !out.status.success() {
let why = String::from_utf8_lossy(&out.stderr).trim().to_owned();
self.last_error = Some(format!("sing-box refused the rendered config: {why}"));
self.sup.note(SOCKS_UNIT, format!("proxy-suite: sing-box refused the new config, keeping the old one: {why}"));
anyhow::bail!("sing-box refused the rendered config: {why}");
// XRay keeps its geodata beside xray.exe (the component's directory).
let asset_dir = main_program.parent().map(|d| d.to_string_lossy().into_owned());
let out = if backend == Backend::Xray {
let mut cmd = tokio::process::Command::new(&main_program);
cmd.args(["run", "-test", "-c"]).arg(&candidate);
if let Some(dir) = &asset_dir {
cmd.env("XRAY_LOCATION_ASSET", dir);
}
cmd.output().await?
} else {
tokio::process::Command::new(&main_program).args(["check", "-c"]).arg(&candidate).output().await?
};
if !out.status.success() {
let name = if backend == Backend::Xray { "xray" } else { "sing-box" };
// XRay reports on stdout as well.
let text = if backend == Backend::Xray { [&out.stdout[..], &out.stderr[..]].concat() } else { out.stderr.clone() };
let why = String::from_utf8_lossy(&text).trim().to_owned();
self.last_error = Some(format!("{name} refused the rendered config: {why}"));
self.sup.note(SOCKS_UNIT, format!("proxy-suite: {name} refused the new config, keeping the old one: {why}"));
anyhow::bail!("{name} refused the rendered config: {why}");
}
if !same_content(&main_path, &main_json) {
std::fs::rename(&candidate, &main_path)?;
@@ -438,7 +450,7 @@ impl Service {
name: SOCKS_UNIT.into(),
program: main_program,
args,
env: Vec::new(),
env: if backend == Backend::Xray { asset_dir.map(|d| vec![("XRAY_LOCATION_ASSET".to_owned(), d)]).unwrap_or_default() } else { Vec::new() },
cwd: Some(run.clone()),
generation: digest(&main_json),
});
+28
View File
@@ -50,6 +50,12 @@ fn with_sep(p: &Path) -> String {
/// The unit for zapret-discord-youtube: the preset's winws.exe line, with the lists in the
/// service's run directory (the release's own, the user's entries added) and the game
/// filter. `program` is the verified winws.exe.
/// The TUN's packets, left out of WinDivert's filter, when the proxy has a TUN.
fn tun_keep_off(cfg: &Config) -> Option<String> {
let p = &cfg.proxy;
(p.enable && p.tun.enable).then(|| zapret::tun_exclusion(&p.tun.address, p.ipv6.then_some(ps_core::render::TUN_IPV6_ADDRESS))).flatten()
}
pub fn discord_youtube_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<UnitSpec> {
let y = &cfg.zapret.discord_youtube;
let component = paths.bin().join("zapret");
@@ -113,6 +119,26 @@ pub fn discord_youtube_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Re
if cfg.debug.log_level != ps_core::config::LogLevel::Warn {
argv.insert(0, "--debug=1".into());
}
// Beside the TUN: Flowseal's winws takes no filter part ANDed with the rest, so its whole
// filter, as it saves it itself for these arguments, with the TUN's packets left out.
let mut filter = String::new();
if cfg!(windows)
&& let Some(keep_off) = tun_keep_off(cfg)
{
let saved = paths.run().join("zapret").join("winws-own-filter.txt");
let _ = std::fs::remove_file(&saved);
let mut cmd = std::process::Command::new(&program);
cmd.arg(format!("--wf-save={}", saved.display())).args(&argv).current_dir(&bin_dir);
cmd.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
#[cfg(windows)]
std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); // CREATE_NO_WINDOW
let _ = cmd.status();
let own = std::fs::read_to_string(&saved).context("winws did not save its filter (--wf-save), to leave the TUN out of it")?;
filter = format!("({})\nand\n({keep_off})\n", own.trim());
let file = paths.run().join("zapret").join("winws-filter.txt");
write_atomic(&file, filter.as_bytes())?;
argv = zapret::with_raw_filter(&argv, &file.to_string_lossy());
}
// A change of the arguments or of a list winws reads is a restart.
let generation = {
use sha2::{Digest, Sha256};
@@ -121,6 +147,7 @@ pub fn discord_youtube_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Re
h.update(a.as_bytes());
h.update(b"\n");
}
h.update(filter.as_bytes());
for f in ["list-general-user.txt", "list-exclude-user.txt", "ipset-exclude-user.txt", "ipset-all.txt"].iter().map(|f| f.to_string()).chain(rule_files) {
h.update(std::fs::read(lists.join(&f)).unwrap_or_default());
}
@@ -214,6 +241,7 @@ pub fn zapret2_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<Uni
exclude: exclude.to_string_lossy().into_owned(),
auto: auto.to_string_lossy().into_owned(),
extras,
keep_off: tun_keep_off(cfg),
};
let argv = zapret2::args(z, &source, &p, cfg.debug.zapret2.packets).map_err(anyhow::Error::msg)?;
// Read inside winws2 by z2k's state layer, the detector and the per-site key.