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:
1 parent
2dd563ed61
commit
d675fdddb5
15 files changed
+831
-34
No files matched your search
@@ -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,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 })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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::*;
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user