windows: zapret2's verdicts route the proxy; options kept to what they are

As upstream's direct-sync: from zapret2's lists and the detector's
verdicts, two rule-sets sing-box reloads, rebuilt every ten seconds and
before it starts: what zapret2 cannot fix (every strategy failed for a
site, or an address leaves connections unanswered) through the proxy
(zapret2.proxyFallback), after the explicit rules and autoProxy's; what
it fixes direct, so it sees it (directSync), unless learned from
transfers cut short. all-bypass and all-proxy as upstream.

The options file winws2 reads (one a line) refuses an option holding a
control character, which would read as more options than it is; and
zapret2.ports.extraTcp/extraUdp, which join its options as written, are
ports or ranges within 1-65535 (validated, and filtered again).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-27 18:16:48 +03:00
1 parent 9eed225ccc
commit 514ffb97ca
10 files changed
+305 -27

No files matched your search

+2 -3
View File
@@ -21,7 +21,7 @@ tray icon) or with `proxy-ctl`, as upstream's is.
| Local proxy | SOCKS5/HTTP on `127.0.0.1:1080` through sing-box (or the hybrid sing-box + XRay backend) |
| Outbounds | links (vless/REALITY/TLS, vmess, trojan, shadowsocks, hysteria2, tuic, anytls, naive, socks, http), raw JSON, subscriptions, groups (failover, urltest, selector), chains, pins, route modes, routing rules by site, address, geodata, rule set or **program** |
| zapret | Flowseal's [zapret-discord-youtube](https://github.com/Flowseal/zapret-discord-youtube) release: `winws.exe` with any of its `general*.bat` presets, your lists, the game filter, and `hostlistRules` (a strategy of its own for a group of sites, copied from a preset or given) |
| zapret2 | `winws2.exe` from bol-van's [zapret-win-bundle](https://github.com/bol-van/zapret-win-bundle) with [nfqws2-keenetic](https://github.com/nfqws/nfqws2-keenetic)'s strategies or [z2k](https://github.com/necronicle/z2k)'s (made by z2k's own generator, per category: YouTube, Discord, QUIC, the RKN list), and upstream's Lua around them: each site's working strategy kept across restarts, strategies keyed by site (the public suffix list), and the extended detector, which also learns sites blocked only some of the time and requests that never get an answer. The server's TLS replies reach the detectors through a WinDivert filter part; a download stalling mid-way (the 16 KB cutoff) is not seen on Windows, as WinDivert cannot hand over a flow's first packets alone |
| zapret2 | `winws2.exe` from bol-van's [zapret-win-bundle](https://github.com/bol-van/zapret-win-bundle) with [nfqws2-keenetic](https://github.com/nfqws/nfqws2-keenetic)'s strategies or [z2k](https://github.com/necronicle/z2k)'s (made by z2k's own generator, per category: YouTube, Discord, QUIC, the RKN list), and upstream's Lua around them: each site's working strategy kept across restarts, strategies keyed by site (the public suffix list), and the extended detector, which also learns sites blocked only some of the time and requests that never get an answer. The server's TLS replies reach the detectors through a WinDivert filter part; a download stalling mid-way (the 16 KB cutoff) is not seen on Windows, as WinDivert cannot hand over a flow's first packets alone. By its detector's verdicts the proxy routes too: what zapret2 cannot fix goes through the proxy (`proxyFallback`), what it fixes goes direct so it sees it (`directSync`) |
| tg-ws-proxy | Flowseal's [tg-ws-proxy](https://github.com/Flowseal/tg-ws-proxy), the headless proxy, on a bundled Python |
| Tor | `tor`: the Tor Project's own Windows build (the Expert Bundle, signed, pinned), with bridges (obfs4, webtunnel, snowflake, meek, conjure) and, with `asOutbound`, an outbound of the proxy |
| AmneziaWG | `amneziaWg` profiles, from a `.conf`, an AmneziaVPN `vpn://` link or settings. Without `asOutbound`, a **system-wide VPN**: amneziawg-windows's tunnel (amneziawg-go on Wintun, built from its source) as a Windows service of its own, with its routes, DNS and, for one peer that takes everything, its firewall blocking what leaves outside the tunnel; on and off in the app or `proxy-ctl awg on|off`. As outbounds: `"userspace"` (wireproxy-awg, built from upstream's source, AmneziaWG's obfuscation kept, no driver) or `"singBox"` (plain WireGuard). WARP devices take either kind too |
@@ -33,8 +33,7 @@ tray icon) or with `proxy-ctl`, as upstream's is.
| The app | **Proxy Suite** in the Start Menu, and a tray icon from sign-in: the proxy, DPI bypass and Telegram proxy at a glance and a click; outbounds, subscriptions and the routing mode; zapret's presets and sites; tg-ws-proxy's links; whitelist-bypass's joiners and creators (links, logins); autoProxy's routes, probes and exits; the logs; **every option** in its JSON editor, checked by the service before it takes it; the system proxy |
Not in this release, still to come: Tor's onion service,
the kill switch, server inbounds, the XRay-only backend, zapret2's proxyFallback (the proxy
carrying what it cannot fix) and its 16 KB cutoff probe. Their options are accepted (they are upstream's), but the
the kill switch, server inbounds, the XRay-only backend and zapret2's 16 KB cutoff probe. Their options are accepted (they are upstream's), but the
service says, in its status and in the app, that it does not run them yet.
Needs 64-bit Windows 10 (1903 or later) or 11.
+32 -7
View File
@@ -137,13 +137,8 @@ fn not_ported(cfg: &Config, v: &mut Issues) {
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 && z.engine == ZapretEngine::Zapret2 {
if z.zapret2.proxy_fallback {
v.warn("zapret.zapret2.proxyFallback", "the proxy carrying what zapret2 cannot fix is not on Windows yet: such sites stay direct");
}
if z.zapret2.cutoff.enable {
v.warn("zapret.zapret2.cutoff.enable", "the 16 KB cutoff probe is not on Windows yet");
}
if z.enable && z.engine == ZapretEngine::Zapret2 && z.zapret2.cutoff.enable {
v.warn("zapret.zapret2.cutoff.enable", "the 16 KB cutoff probe is not on Windows yet");
}
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");
@@ -504,6 +499,26 @@ fn tunnels(cfg: &Config, v: &mut Issues) {
fn zapret(cfg: &Config, v: &mut Issues) {
let z = &cfg.zapret;
// They join winws2's options as written.
let p = &z.zapret2.ports;
for (path, values) in [("zapret.zapret2.ports.extraTcp", &p.extra_tcp), ("zapret.zapret2.ports.extraUdp", &p.extra_udp)] {
for value in values {
let text = match value {
serde_json::Value::String(s) => s.clone(),
other => other.to_string(),
};
if !crate::zapret2::port_spec_ok(text.trim()) {
v.error(path, format!("'{text}' is not a port or a range (N, or N-M, within 1-65535)"));
}
}
}
for (path, list) in [("zapret.zapret2.ports.tcp", &p.tcp), ("zapret.zapret2.ports.udp", &p.udp)] {
if let Some(list) = list
&& !list.split(',').all(|x| crate::zapret2::port_spec_ok(x.trim().replace(':', "-").as_str()))
{
v.error(path, "ports and ranges, comma-separated (N, or N-M, within 1-65535)");
}
}
if !z.enable {
return;
}
@@ -773,6 +788,16 @@ mod tests {
}
}
#[test]
fn zapret2_extra_ports_are_ports() {
let mut cfg = Config::default();
cfg.zapret.zapret2.ports.extra_tcp = vec![serde_json::json!(8443), serde_json::json!("50000-50099"), serde_json::json!("443\n--lua-init=@x.lua")];
cfg.zapret.zapret2.ports.udp = Some("443,590:600".into());
let errs = errors(&cfg);
assert_eq!(errs.iter().filter(|e| e.starts_with("zapret.zapret2.ports")).count(), 1, "{errs:?}");
assert!(crate::zapret2::port_spec_ok("1-65535") && !crate::zapret2::port_spec_ok("0") && !crate::zapret2::port_spec_ok("9-1") && !crate::zapret2::port_spec_ok("443 x"));
}
#[test]
fn whitelist_bypass_names_are_checked_while_it_is_off() {
let mut cfg = Config::default();
+4
View File
@@ -105,6 +105,10 @@ pub struct Env {
pub windows: bool,
/// Where autoProxy's learned rule-sets are (one file per exit), when it runs.
pub autoproxy_rules_dir: Option<String>,
/// zapret2's rule-sets (ps_core::zapret2::routing): what it fixes, sent direct
/// (`zapret.directSync`), and what it cannot, for the proxy (`zapret2.proxyFallback`).
pub zapret2_direct_rule_set: Option<String>,
pub zapret2_proxy_rule_set: Option<String>,
}
pub struct Input<'a> {
@@ -146,6 +146,21 @@ pub(super) fn config(input: &Input, asm: &Assembly, probe_exits: &[ProbeExit], w
let mut rule_sets = route.rule_set;
let mut dns_rules = route.dns_rules;
autoproxy::apply(input, probe_exits, &mut inbounds, &mut rules, route.pin_at, &mut rule_sets, &mut dns_rules, route.mode);
// zapret2's: what it cannot fix through the proxy, after the explicit rules and autoProxy's,
// ahead of the hosts it does fix, which go direct so it sees them. all-bypass sends
// everything direct, and all-proxy keeps no direct lists.
if let Some(path) = &env.zapret2_proxy_rule_set
&& route.mode != super::RouteMode::AllBypass
{
rule_sets.push(json!({ "type": "local", "format": "source", "tag": "zapret-unfixable", "path": path }));
rules.push(json!({ "rule_set": ["zapret-unfixable"], "outbound": "proxy" }));
}
if let Some(path) = &env.zapret2_direct_rule_set
&& !matches!(route.mode, super::RouteMode::AllBypass | super::RouteMode::AllProxy)
{
rule_sets.push(json!({ "type": "local", "format": "source", "tag": "zapret-hosts", "path": path }));
rules.push(json!({ "rule_set": ["zapret-hosts"], "outbound": "direct" }));
}
let after_sniff = rules.iter().position(|r| r["action"] == "sniff").map_or(0, |i| i + 1);
rules.insert(after_sniff, json!({ "inbound": ["proxy-suite-test-in"], "outbound": "proxy-suite-test" }));
if hybrid {
+154 -9
View File
@@ -1,14 +1,16 @@
//! zapret2 on Windows: winws2 (WinDivert) with the strategies upstream's module gives nfqws2
//! (NFQUEUE). The strategy source is nfqws2-keenetic, read and patched as upstream's
//! `zapret2/sources.nix` does; the profiles, markers, circular defaults and ports follow
//! upstream's `zapret2/runtime.nix` and zapret2's own `common/list.sh`.
//! (NFQUEUE): nfqws2-keenetic's, read and patched as upstream's `zapret2/sources.nix` does, or
//! z2k's, made by its own generator (tools/build-zapret2-extras.sh); the profiles, markers,
//! circular defaults, ports and Lua layers follow upstream's `zapret2/runtime.nix`, and the
//! routing by the detector's verdicts its `direct-sync.template.sh`.
//!
//! What differs on Windows: WinDivert's port filters (`--wf-tcp-out`, `--wf-udp-out`) take
//! the place of the queue's rules, and there are no marks. winws2 drops to Low integrity once
//! it runs, so the learned list lives in a directory the service labels Low for it (winws2's
//! own `--writable` insists on making the directory, which must already hold the list).
//! Learning is nfqws2's own autohostlist; upstream's detector (`detect.lua`,
//! `extendedDetection`) and z2k come later.
//! the place of the queue's rules, a filter part hands the detectors the server's TLS
//! records in place of the queue's packet windows, and there are no marks. winws2 drops to
//! Low integrity once it runs, so what it writes lives in a directory the service labels Low
//! for it (winws2's own `--writable` insists on making the directory).
use std::collections::BTreeMap;
use crate::config::{StrategySource, Zapret2};
@@ -297,13 +299,25 @@ fn circular_fill(z: &Zapret2, token: &str) -> String {
t
}
/// A port or a range as winws2 takes one: `N` or `N-M`, within 1-65535.
pub fn port_spec_ok(spec: &str) -> bool {
let num = |s: &str| !s.is_empty() && s.len() <= 5 && s.chars().all(|c| c.is_ascii_digit()) && s.parse::<u32>().is_ok_and(|n| (1..=65535).contains(&n));
match spec.split_once('-') {
Some((a, b)) => num(a) && num(b) && a.parse::<u32>().ok() <= b.parse::<u32>().ok(),
None => num(spec),
}
}
/// `ports.extraTcp`/`extraUdp` as winws2's list: numbers and ranges alone (validated already;
/// anything else dropped here too, as it joins winws2's options).
fn port_list(values: &[serde_json::Value]) -> String {
values
.iter()
.map(|v| match v {
serde_json::Value::String(s) => s.clone(),
serde_json::Value::String(s) => s.trim().to_owned(),
other => other.to_string(),
})
.filter(|s| port_spec_ok(s))
.collect::<Vec<_>>()
.join(",")
}
@@ -504,6 +518,119 @@ pub fn args(z: &Zapret2, source: &Source, p: &Paths, debug_packets: bool) -> Res
Ok(opt)
}
// --- what the proxy does with zapret2's verdicts (upstream's direct-sync.template.sh) -------
/// An entry a rule-set can take: an IPv4 or IPv6 address, or a name of two labels at least
/// (a bare "com" would send the whole TLD past the proxy). The zapret scope writes the lists.
fn host_valid(h: &str) -> bool {
if let Ok(ip) = h.parse::<std::net::IpAddr>() {
return ip.is_ipv4() || !h.contains('%');
}
let label_ok = |l: &str| {
!l.is_empty()
&& l.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
&& !l.starts_with('-')
&& !l.ends_with('-')
};
h.len() <= 253 && h.contains('.') && h.split('.').all(label_ok) && !h.chars().all(|c| c.is_ascii_digit() || c == '.')
}
/// nfqws hostlists: one host a line, `#` comments, `^` for the name alone.
fn hosts(text: &str) -> Vec<String> {
text.lines()
.map(|l| l.trim().to_ascii_lowercase())
.map(|l| l.trim_start_matches('^').to_owned())
.filter(|l| !l.is_empty() && !l.starts_with('#') && host_valid(l))
.collect()
}
/// detect.lua's verdicts ("kind<TAB>name<TAB>proto<TAB>..."), the last per name and proto:
/// (name, proto) -> kind.
fn verdicts(text: &str) -> BTreeMap<(String, String), String> {
let mut out = BTreeMap::new();
for line in text.lines() {
let f: Vec<&str> = line.split('\t').collect();
if f.len() < 3 || !host_valid(f[1]) {
continue;
}
out.insert((f[1].to_owned(), f[2].to_owned()), f[0].to_owned());
}
out
}
fn named(v: &BTreeMap<(String, String), String>, kind: &str, proto: &str) -> Vec<String> {
v.iter().filter(|((_, p), k)| k.as_str() == kind && p == proto).map(|((n, _), _)| n.clone()).collect()
}
/// A name and a site key cover each other either way round: www.notion.so and notion.so.
fn covers(a: &str, b: &str) -> bool {
a == b || a.ends_with(&format!(".{b}")) || b.ends_with(&format!(".{a}"))
}
fn is_ip(h: &str) -> bool {
h.parse::<std::net::IpAddr>().is_ok()
}
fn cidr(ips: &[String]) -> Vec<String> {
ips.iter().map(|ip| if ip.contains(':') { format!("{ip}/128") } else { format!("{ip}/32") }).collect()
}
/// The two rule-sets the proxy routes by, from zapret2's lists and its detector's verdicts:
/// `direct`, the hosts zapret2 handles, sent direct so it sees them (the pinned ones, and the
/// learned ones once a strategy got through for them, unless learned from transfers cut short);
/// `proxy`, what it cannot fix, for the proxy to carry (sites every strategy failed for, all
/// of a site's TCP or only its QUIC, and addresses that leave connections unanswered).
/// `auto` is the learned list, none when learning is off.
pub fn routing(user: &str, auto: Option<&str>, excluded: &str, verdicts_text: &str) -> (serde_json::Value, serde_json::Value) {
use serde_json::json;
let v = verdicts(verdicts_text);
let works = named(&v, "works", "tcp");
// Learned from a transfer cut short: success is judged on the first 4 KB, which the
// cutoff lets through, so "works" proves nothing for it.
let stalls = named(&v, "stalls", "cutoff");
let excluded = hosts(excluded);
let mut direct: Vec<String> = hosts(user);
direct.extend(
hosts(auto.unwrap_or(""))
.into_iter()
.filter(|h| works.iter().any(|w| covers(h, w)) && !stalls.iter().any(|s| covers(h, s))),
);
direct.sort();
direct.dedup();
direct.retain(|h| !excluded.contains(h));
let (ips, names): (Vec<String>, Vec<String>) = direct.into_iter().partition(|h| is_ip(h));
let mut rules = Vec::new();
if !names.is_empty() {
rules.push(json!({ "domain_suffix": names }));
}
if !ips.is_empty() {
rules.push(json!({ "ip_cidr": cidr(&ips) }));
}
let direct = json!({ "version": 1, "rules": rules });
// A site keyed by its address (no name seen) goes by address.
let tcp = named(&v, "unfixable", "tcp");
let udp = named(&v, "unfixable", "udp");
let (tcp_ips, tcp_names): (Vec<String>, Vec<String>) = tcp.into_iter().partition(|h| is_ip(h));
let (udp_ips, udp_names): (Vec<String>, Vec<String>) = udp.into_iter().partition(|h| is_ip(h));
let mut blocked = named(&v, "blocked", "ip");
blocked.extend(tcp_ips);
let mut rules = Vec::new();
if !tcp_names.is_empty() {
rules.push(json!({ "domain_suffix": tcp_names }));
}
if !udp_names.is_empty() {
rules.push(json!({ "network": ["udp"], "port": [443], "domain_suffix": udp_names }));
}
if !udp_ips.is_empty() {
rules.push(json!({ "network": ["udp"], "port": [443], "ip_cidr": cidr(&udp_ips) }));
}
if !blocked.is_empty() {
rules.push(json!({ "ip_cidr": cidr(&blocked) }));
}
(direct, json!({ "version": 1, "rules": rules }))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -555,6 +682,24 @@ UDP_PORTS=443,590:600
}
}
#[test]
fn verdicts_route_what_zapret2_fixes_direct_and_the_rest_by_the_proxy() {
let user = "^pinned.example\n# a comment\ncom\n203.0.113.5\nbad entry\n";
let auto = "learned.example\nnotyet.example\ncut.example\nleft.example\n";
let verdicts = "works\tlearned.example\ttcp\t\t1\nworks\tcut.example\ttcp\t\t1\nstalls\tcut.example\tcutoff\t\t2\n\
works\tleft.example\ttcp\t\t1\nunfixable\tdead.example\ttcp\t\t3\nunfixable\tquic.example\tudp\t\t3\n\
blocked\t198.51.100.7\tip\t\t4\nunfixable\tgone.example\ttcp\t\t3\nretry\tgone.example\ttcp\t\t5\n";
let (direct, proxy) = routing(user, Some(auto), "left.example\n", verdicts);
assert_eq!(direct["rules"][0]["domain_suffix"], serde_json::json!(["learned.example", "pinned.example"]));
assert_eq!(direct["rules"][1]["ip_cidr"], serde_json::json!(["203.0.113.5/32"]));
assert_eq!(proxy["rules"][0]["domain_suffix"], serde_json::json!(["dead.example"]), "gone.example's last verdict clears it");
assert_eq!(proxy["rules"][1], serde_json::json!({ "network": ["udp"], "port": [443], "domain_suffix": ["quic.example"] }));
assert_eq!(proxy["rules"][2]["ip_cidr"], serde_json::json!(["198.51.100.7/32"]));
// Learning off: the pinned ones alone.
let (direct, _) = routing(user, None, "", verdicts);
assert_eq!(direct["rules"][0]["domain_suffix"], serde_json::json!(["pinned.example"]));
}
#[test]
fn the_extended_detector_learns_in_place_of_nfqws2() {
let z = Zapret2 { strategy_log: true, ..Default::default() };
+26
View File
@@ -289,3 +289,29 @@ fn auto_proxy_never_routes_what_it_excludes() {
);
check_sing_box(&sb, &dir);
}
#[test]
fn zapret2s_rule_sets_follow_autoproxy_and_the_mode() {
let dir = scratch("zapret2-sync");
let (direct, proxy) = (dir.join("direct.json"), dir.join("proxy.json"));
std::fs::write(&direct, r#"{"version":1,"rules":[{"domain_suffix":["fixed.example"]}]}"#).unwrap();
std::fs::write(&proxy, r#"{"version":1,"rules":[{"domain_suffix":["unfixable.example"]}]}"#).unwrap();
let cfg = base();
let mut e = env(&dir);
e.windows = false;
e.zapret2_direct_rule_set = Some(direct.to_string_lossy().into());
e.zapret2_proxy_rule_set = Some(proxy.to_string_lossy().into());
let render_with = |state: &State| render(&Input { cfg: &cfg, state, subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun: false }).unwrap().sing_box.unwrap();
let sb = render_with(&State::default());
let rules = sb["route"]["rules"].as_array().unwrap();
let n = rules.len();
assert_eq!(rules[n - 2], json!({ "rule_set": ["zapret-unfixable"], "outbound": "proxy" }));
assert_eq!(rules[n - 1], json!({ "rule_set": ["zapret-hosts"], "outbound": "direct" }));
check_sing_box(&sb, &dir);
// all-proxy keeps no direct lists; all-bypass sends everything direct.
let mut state = State { route_mode: Some(RouteMode::AllProxy), ..Default::default() };
let tags = |sb: &Value| sb["route"]["rules"].as_array().unwrap().iter().filter_map(|r| r["rule_set"][0].as_str().map(str::to_owned)).collect::<Vec<_>>();
assert_eq!(tags(&render_with(&state)), ["zapret-unfixable"]);
state.route_mode = Some(RouteMode::AllBypass);
assert!(tags(&render_with(&state)).is_empty());
}
+1
View File
@@ -108,6 +108,7 @@ pub async fn run(
tokio::spawn(autoproxy::runner(shared.clone()));
tokio::spawn(autoproxy::sample(shared.clone()));
tokio::spawn(autoproxy::sample_slow(shared.clone()));
tokio::spawn(zapret::sync_loop(shared.clone()));
// First fetches: what the configuration needs and has not got yet.
{
let shared = shared.clone();
+5 -1
View File
@@ -144,6 +144,8 @@ impl Service {
ssh_host_keys: if cfg.ssh_proxy.enable { crate::ssh::host_keys(cfg, |f| std::fs::read_to_string(f).ok()) } else { Vec::new() },
windows: cfg!(windows),
autoproxy_rules_dir: cfg.proxy.auto_proxy.enable.then(|| crate::autoproxy::rules_dir(paths).to_string_lossy().into_owned()),
zapret2_direct_rule_set: crate::zapret::rule_set_paths(cfg, paths).0,
zapret2_proxy_rule_set: crate::zapret::rule_set_paths(cfg, paths).1,
}
}
@@ -384,10 +386,12 @@ impl Service {
for w in &rendered.warnings {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: warning: {w}"));
}
// sing-box refuses a local rule-set file that is not there: autoProxy's, written first.
// sing-box refuses a local rule-set file that is not there: autoProxy's and zapret2's,
// written first.
if !rendered.probe_exits.is_empty() {
crate::autoproxy::publish(&rendered.probe_exits, &crate::autoproxy::load(self.paths()))?;
}
crate::zapret::sync_rule_sets(self.cfg(), self.paths())?;
let backend = self.cfg().proxy.backend;
let main_program = match backend {
+64 -5
View File
@@ -236,14 +236,18 @@ pub fn zapret2_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<Uni
// In a file winws2 reads (`@file`, its only argument): z2k's strategies alone run past
// the 32767 characters a Windows command line holds.
let file = paths.run().join("winws2.conf");
write_atomic(&file, options_file(&argv).as_bytes()).with_context(|| format!("writing {}", file.display()))?;
write_atomic(&file, options_file(&argv)?.as_bytes()).with_context(|| format!("writing {}", file.display()))?;
Ok(UnitSpec { name: UNIT.into(), program, args: vec![format!("@{}", file.display())], env, cwd: Some(component), generation })
}
/// winws2's options as its `@file` takes them: one a line, quoted when it holds a space.
pub fn options_file(argv: &[String]) -> String {
/// winws2's options as its `@file` takes them: one a line, quoted when it holds a space. One
/// holding a line break would be read as more options than it is: refused.
pub fn options_file(argv: &[String]) -> Result<String> {
let mut out = String::new();
for a in argv {
if a.contains(char::is_control) {
bail!("a winws2 option holds a control character: {:?}", a.chars().take(80).collect::<String>());
}
if a.contains(char::is_whitespace) || a.contains('"') {
out.push('"');
out.push_str(&a.replace('\\', "\\\\").replace('"', "\\\""));
@@ -253,7 +257,61 @@ pub fn options_file(argv: &[String]) -> String {
}
out.push('\n');
}
out
Ok(out)
}
/// zapret2's rule-sets for the proxy (ps_core::zapret2::routing), when it runs: what it fixes,
/// sent direct (`zapret.directSync`), and what it cannot, for the proxy
/// (`zapret2.proxyFallback`).
pub fn rule_set_paths(cfg: &Config, paths: &Paths) -> (Option<String>, Option<String>) {
let on = cfg.enable && cfg.zapret.enable && cfg.zapret.engine == ZapretEngine::Zapret2;
let dir = paths.root.join("zapret2-direct");
let file = |name: &str| dir.join(name).to_string_lossy().into_owned();
(
(on && cfg.zapret.direct_sync.enable).then(|| file("direct.json")),
(on && cfg.zapret.zapret2.proxy_fallback).then(|| file("proxy.json")),
)
}
/// The rule-sets rebuilt from zapret2's lists and its detector's verdicts, each written only
/// when it changed (sing-box reloads a rule-set file replaced). Whether either did.
pub fn sync_rule_sets(cfg: &Config, paths: &Paths) -> Result<bool> {
let (direct, proxy) = rule_set_paths(cfg, paths);
if direct.is_none() && proxy.is_none() {
return Ok(false);
}
let state = paths.root.join("zapret2");
let read = |p: PathBuf| std::fs::read_to_string(p).unwrap_or_default();
let auto = cfg.zapret.zapret2.auto_hostlist.enable.then(|| read(state.join("learned").join("zapret-hosts-auto.txt")));
let (d, p) = ps_core::zapret2::routing(
&read(state.join("zapret-hosts-user.txt")),
auto.as_deref(),
&read(state.join("zapret-hosts-user-exclude.txt")),
&read(state.join("learned").join("verdicts.tsv")),
);
let mut changed = false;
for (path, set) in [(direct, d), (proxy, p)] {
let Some(path) = path else { continue };
let path = PathBuf::from(path);
let body = serde_json::to_vec(&set)?;
if std::fs::read(&path).ok().as_deref() != Some(body.as_slice()) {
std::fs::create_dir_all(path.parent().unwrap())?;
write_atomic(&path, &body)?;
changed = true;
}
}
Ok(changed)
}
/// The rule-sets kept in step with what zapret2 learns, every ten seconds.
pub async fn sync_loop(shared: crate::service::Shared) {
loop {
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
let s = shared.lock().await;
if let Err(e) = sync_rule_sets(s.cfg(), s.paths()) {
tracing::warn!("zapret2's rule-sets: {e:#}");
}
}
}
/// A path as winws2's Lua takes it in a colon-separated argument, or opens it from the
@@ -322,7 +380,8 @@ mod tests {
#[test]
fn options_go_one_a_line_quoted_when_spaced() {
let argv: Vec<String> = ["--filter-tcp=443", "--wf-raw-part=inbound and tcp.Payload[0] == 0x16", r#"--x="a""#].map(String::from).into();
assert_eq!(options_file(&argv), "--filter-tcp=443\n\"--wf-raw-part=inbound and tcp.Payload[0] == 0x16\"\n\"--x=\\\"a\\\"\"\n");
assert_eq!(options_file(&argv).unwrap(), "--filter-tcp=443\n\"--wf-raw-part=inbound and tcp.Payload[0] == 0x16\"\n\"--x=\\\"a\\\"\"\n");
assert!(options_file(&["--filter-tcp=443\n--lua-init=@x.lua".to_owned()]).is_err());
}
#[test]
+2 -2
View File
@@ -20,7 +20,7 @@ The desktop app: Proxy Suite now has a window and a tray icon, besides `proxy-ct
`install.cmd` puts it in the Start Menu and starts it at every sign-in, in the tray.
### Also
- zapret2: z2k's strategies (`strategySource = "z2k"`), made by z2k's own generator; upstream's Lua around either source: each site's working strategy kept across restarts, strategies keyed by site, and the extended detector (`autoHostlist.extendedDetection`), which also learns sites blocked only some of the time and requests that never get an answer. On the DPI bypass page too.
- zapret2: z2k's strategies (`strategySource = "z2k"`), made by z2k's own generator; upstream's Lua around either source: each site's working strategy kept across restarts, strategies keyed by site, and the extended detector (`autoHostlist.extendedDetection`), which also learns sites blocked only some of the time and requests that never get an answer. By its verdicts the proxy carries what zapret2 cannot fix (`proxyFallback`) and sends what it fixes direct (`directSync`). On the DPI bypass page too.
- zapret's `hostlistRules`: a group of sites with its own strategy, copied from a preset (or another one, `configName`) or given as `nfqwsArgs`, ahead of the preset's own; every preset with them checked by Flowseal's `winws.exe`.
- The SSH tunnel (`sshProxy`): Windows' own OpenSSH as a SOCKS listener for other programs, and, with `asOutbound`, an outbound of the proxy. Needs Windows' "OpenSSH Client" (there by default since Windows 10 1809).
- Tor (`tor`): the Tor Project's own Windows build, with bridges (obfs4, webtunnel, snowflake, meek, conjure) and, with `asOutbound`, an outbound of the proxy.
@@ -41,7 +41,7 @@ Download `ProxySuite-0.2.0-pre.1-windows-x64-setup.exe` and run it (its SHA-256
The zip is still there, the same files with `install.cmd`.
### Not yet
Tor's onion service, the kill switch, server inbounds, the XRay-only backend, zapret2's proxyFallback and its 16 KB cutoff probe.
Tor's onion service, the kill switch, server inbounds, the XRay-only backend and zapret2's 16 KB cutoff probe.
### Note
Unlike upstream, the signed-in user may change every setting by default (`userControl`), except the ones that could run programs or read files as SYSTEM: those always need an administrator. On a shared computer, restrict `userControl.scopes`.