windows: zapret2's 16 KB cutoff probe
Upstream's cutoff.nix and cutoff-probe.template.sh: z2k-detect (built from z2k's pinned source for Windows, in zapret2-extras) finds the networks this line cuts after ~16 KB, and with z2k's own strategies a whitelisted name per network; z2k-tcp16.lua inside winws2 reads the maps (Z2K_TCP16_*, their digest in the environment so a new map restarts winws2); what no name fixes goes to the zapret-cutoff rule-set for the proxy (cutoff.proxyFallback). Upstream keeps zapret2 off the probe with an nft cgroup rule. Here z2k-detect is patched to dial from a local port range (Z2K_TCP16_LOCAL_PORTS, 44000-47999, below Windows' dynamic range) and winws2 gets --wf-raw-filter leaving that range alone; under the TUN the probe and the service's own lookups of the line's network go direct. Rounds as upstream's timer: 5 min after start, every 10 min, probing when the line's network (ipinfo.io and ifconfig.co agreeing) changed or a day passed. Request::ZapretCutoff, proxy-ctl zapret cutoff [probe], a card on the DPI page. Verified live on a line that cuts (25 networks, a name for each), the Windows z2k-detect under Wine, winws2 --dry-run and --wf-save with the filter. gui-shot's scroll takes a count. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d33f05c62c
commit
803e18db9d
19 files changed
+721
-18
No files matched your search
+5
-3
@@ -22,7 +22,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. 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`) |
|
||||
| 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`). The **16 KB cutoff probe** (`zapret2.cutoff`, on by default): some lines cut TLS to certain hosting networks after about 16 KB, which no strategy fixes; z2k's probe (`z2k-detect`, built from its source) finds them daily or when the line's network changes, and with z2k's strategies a name that gets through for each, which z2k puts into a fake hello; the networks no name fixes go through the proxy, by address. Its connections leave from ports winws2 is told to leave alone. `proxy-ctl zapret cutoff [probe]`, or the DPI bypass page |
|
||||
| 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 |
|
||||
@@ -34,7 +34,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; a light and a dark theme (or as Windows is set); a newer release installed from its Overview |
|
||||
|
||||
Not in this release, still to come: Tor's onion service,
|
||||
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
|
||||
the kill switch, server inbounds and the XRay-only backend. 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.
|
||||
@@ -62,7 +62,8 @@ DPI bypass, which runs on Windows only, shows as inactive.
|
||||
| Service, API, `proxy-ctl` | end to end on Linux: a real sing-box Shadowsocks server, the service, `proxy-ctl` adding the outbound, a page fetched through the local proxy |
|
||||
| Windows build: service, named pipe, its ACL, caller identification, component hashes, supervisor | under Wine (`tools/wine-e2e.sh`) |
|
||||
| zapret arguments | **every** preset of the release, both game filters, checked by the release's own `winws.exe --dry-run` under Wine (`tools/winws-dry-run.sh`) |
|
||||
| zapret2 arguments | checked by `winws2.exe --dry-run` under Wine |
|
||||
| zapret2 arguments | checked by `winws2.exe --dry-run` under Wine, the cutoff probe's filter part included |
|
||||
| 16 KB cutoff probe | on this test machine's line, which does cut TLS at 16 KB to some networks: the service ran z2k-detect (its Linux build, the same patched source), which found 25 networks cut off and a name for each; its connections left from the probe's ports only; the maps, the line's network and the rule-set written, shown by `proxy-ctl zapret cutoff` and the app. The Windows build runs under Wine; winws2 leaving its connections alone needs real Windows |
|
||||
| tg-ws-proxy | runs and listens under Wine |
|
||||
| SSH tunnel | end to end on Linux: an sshd of the test's own, a page through the `ssh -D` listener and through sing-box's SSH outbound, each logging in with the service's copy of the key (`an_ssh_tunnel`) |
|
||||
| Tor | its Windows `tor.exe` (under Wine) accepts the torrc the service writes, bridges and transports included; on Linux the service runs Tor with it and Tor starts bootstrapping (where Tor's relays are blocked, it needs bridges) |
|
||||
@@ -140,6 +141,7 @@ proxy-ctl zapret game-filter all
|
||||
# zapret2 instead:
|
||||
proxy-ctl config get > config.json # set "zapret": { "enable": true, "engine": "zapret2" }
|
||||
proxy-ctl config set config.json
|
||||
proxy-ctl zapret cutoff # the networks this line cuts off after 16 KB (probe: now)
|
||||
|
||||
# Telegram's WebSocket proxy:
|
||||
proxy-ctl config get > config.json # set "tgWsProxy": { "enable": true }
|
||||
|
||||
@@ -127,7 +127,7 @@
|
||||
"sources": []
|
||||
},
|
||||
"zapret2-extras": {
|
||||
"version": "2026.10.27+z2k.7beb975",
|
||||
"version": "2026.10.28+z2k.7beb975",
|
||||
"license": "MIT (z2k, proxy-suite's Lua); MPL-2.0 (the public suffix list)",
|
||||
"homepage": "https://github.com/necronicle/z2k",
|
||||
"bundled": true,
|
||||
|
||||
@@ -127,3 +127,29 @@ impl Client {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A Unix time as `YYYY-MM-DD HH:MM UTC`.
|
||||
pub fn utc(ts: u64) -> String {
|
||||
let (days, secs) = ((ts / 86400) as i64, ts % 86400);
|
||||
// Howard Hinnant's civil_from_days.
|
||||
let z = days + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z - era * 146_097;
|
||||
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let y = yoe + era * 400 + i64::from(m <= 2);
|
||||
format!("{y:04}-{m:02}-{d:02} {:02}:{:02} UTC", secs / 3600, secs % 3600 / 60)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod time_tests {
|
||||
#[test]
|
||||
fn unix_times_read_as_dates() {
|
||||
assert_eq!(super::utc(0), "1970-01-01 00:00 UTC");
|
||||
assert_eq!(super::utc(951_782_400), "2000-02-29 00:00 UTC");
|
||||
assert_eq!(super::utc(1_793_190_240), "2026-10-28 12:24 UTC");
|
||||
}
|
||||
}
|
||||
@@ -137,9 +137,6 @@ 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 && 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");
|
||||
}
|
||||
|
||||
@@ -109,6 +109,9 @@ pub struct Env {
|
||||
/// (`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>,
|
||||
/// The networks the 16 KB cutoff probe found cut and no name fixes, for the proxy
|
||||
/// (`zapret2.cutoff.proxyFallback`, ps_core::zapret2::cutoff_rules).
|
||||
pub zapret2_cutoff_rule_set: Option<String>,
|
||||
}
|
||||
|
||||
pub struct Input<'a> {
|
||||
|
||||
@@ -155,6 +155,14 @@ pub(super) fn config(input: &Input, asm: &Assembly, probe_exits: &[ProbeExit], w
|
||||
rule_sets.push(json!({ "type": "local", "format": "source", "tag": "zapret-unfixable", "path": path }));
|
||||
rules.push(json!({ "rule_set": ["zapret-unfixable"], "outbound": "proxy" }));
|
||||
}
|
||||
// The networks that cut TLS after 16 KB, which no name fixes: by address, so only for
|
||||
// what the proxy sees by address (the TUN, per-app routing), as upstream's.
|
||||
if let Some(path) = &env.zapret2_cutoff_rule_set
|
||||
&& route.mode != super::RouteMode::AllBypass
|
||||
{
|
||||
rule_sets.push(json!({ "type": "local", "format": "source", "tag": "zapret-cutoff", "path": path }));
|
||||
rules.push(json!({ "rule_set": ["zapret-cutoff"], "outbound": "proxy" }));
|
||||
}
|
||||
if let Some(path) = &env.zapret2_direct_rule_set
|
||||
&& !matches!(route.mode, super::RouteMode::AllBypass | super::RouteMode::AllProxy)
|
||||
{
|
||||
|
||||
@@ -514,10 +514,78 @@ pub fn args(z: &Zapret2, source: &Source, p: &Paths, debug_packets: bool) -> Res
|
||||
if !z.ipv6 {
|
||||
opt.push("--wf-l3=ipv4".into());
|
||||
}
|
||||
// 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()));
|
||||
}
|
||||
opt.extend(body);
|
||||
Ok(opt)
|
||||
}
|
||||
|
||||
// --- the 16 KB cutoff probe (upstream's zapret2/cutoff.nix) ---------------------------------
|
||||
|
||||
/// The local ports the cutoff probe (z2k-detect) connects from, which winws2 leaves alone, as
|
||||
/// upstream's nft rule keeps zapret2 off the probe's cgroup. Below Windows' dynamic range
|
||||
/// (49152-65535), so no other program's connection is given one of them unasked.
|
||||
pub const CUTOFF_PORTS: (u16, u16) = (44000, 47999);
|
||||
|
||||
/// winws2's filter part (`--wf-raw-filter`, ANDed with the rest) that leaves out the probe's
|
||||
/// connections: TCP from or to a local port in [`CUTOFF_PORTS`].
|
||||
pub fn cutoff_filter() -> String {
|
||||
let (lo, hi) = CUTOFF_PORTS;
|
||||
format!("not tcp or (outbound and (tcp.SrcPort < {lo} or tcp.SrcPort > {hi})) or (inbound and (tcp.DstPort < {lo} or tcp.DstPort > {hi}))")
|
||||
}
|
||||
|
||||
/// The networks (AS numbers) a probe found cut off, from its `asn.txt`: a row is one when its
|
||||
/// first field is all digits (upstream's awk; `#` lines are comments).
|
||||
pub fn cut_networks(asn: &str) -> Vec<String> {
|
||||
let mut out: Vec<String> = asn.lines().filter_map(|l| l.split('\t').next()).map(str::trim).filter(|a| is_asn(a)).map(str::to_owned).collect();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// The name that gets through, by network, from its `sni.txt` (`asn<TAB>name`).
|
||||
pub fn network_names(sni: &str) -> BTreeMap<String, String> {
|
||||
sni.lines()
|
||||
.filter_map(|l| {
|
||||
let mut f = l.split('\t');
|
||||
let (a, n) = (f.next()?.trim(), f.next().unwrap_or("").trim());
|
||||
is_asn(a).then(|| (a.to_owned(), n.to_owned()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn is_asn(a: &str) -> bool {
|
||||
!a.is_empty() && a.len() <= 10 && a.bytes().all(|b| b.is_ascii_digit())
|
||||
}
|
||||
|
||||
fn cidr_ok(p: &str) -> bool {
|
||||
let Some((ip, len)) = p.split_once('/') else { return false };
|
||||
match (ip.parse::<std::net::IpAddr>(), len.parse::<u8>()) {
|
||||
(Ok(std::net::IpAddr::V4(_)), Ok(l)) => l <= 32,
|
||||
(Ok(std::net::IpAddr::V6(_)), Ok(l)) => l <= 128,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The rule-set for the proxy (`cutoff.proxyFallback`, upstream's `proxyRules`): the prefixes,
|
||||
/// from z2k's `tcp16_nets.txt` (`asn<TAB>prefix`), of every cut-off network no name fixes.
|
||||
pub fn cutoff_rules(asn: &str, sni: &str, nets: &str) -> serde_json::Value {
|
||||
let cut: std::collections::BTreeSet<String> = cut_networks(asn).into_iter().collect();
|
||||
let named = network_names(sni);
|
||||
let cidrs: Vec<&str> = nets
|
||||
.lines()
|
||||
.filter_map(|l| {
|
||||
let mut f = l.split('\t');
|
||||
let (a, p) = (f.next()?.trim(), f.next()?.trim());
|
||||
(cut.contains(a) && !named.contains_key(a) && cidr_ok(p)).then_some(p)
|
||||
})
|
||||
.collect();
|
||||
let rules = if cidrs.is_empty() { serde_json::json!([]) } else { serde_json::json!([{ "ip_cidr": cidrs }]) };
|
||||
serde_json::json!({ "version": 1, "rules": rules })
|
||||
}
|
||||
|
||||
// --- 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
|
||||
@@ -631,6 +699,31 @@ pub fn routing(user: &str, auto: Option<&str>, excluded: &str, verdicts_text: &s
|
||||
(direct, json!({ "version": 1, "rules": rules }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cutoff_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_probes_maps_read_as_upstreams_awk_reads_them() {
|
||||
let asn = "# cut off on this line\n24940\n16509\n\nAS13335\n";
|
||||
assert_eq!(cut_networks(asn), ["24940", "16509"]);
|
||||
let sni = "# names\n# per network\n24940\t300.ya.ru\nx\ty\n";
|
||||
assert_eq!(network_names(sni), BTreeMap::from([("24940".to_owned(), "300.ya.ru".to_owned())]));
|
||||
let nets = "24940\t91.98.0.0/16\n16509\t3.5.0.0/16\n16509\t2600:1f00::/32\n16509\tnot-a-prefix\n13335\t104.16.0.0/16\n";
|
||||
// Hetzner has a name (z2k puts it in); Amazon none: its prefixes go to the proxy.
|
||||
assert_eq!(cutoff_rules(asn, sni, nets), serde_json::json!({ "version": 1, "rules": [{ "ip_cidr": ["3.5.0.0/16", "2600:1f00::/32"] }] }));
|
||||
assert_eq!(cutoff_rules("", sni, nets), serde_json::json!({ "version": 1, "rules": [] }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_probes_ports_are_left_out_of_winws2s_filter() {
|
||||
let f = cutoff_filter();
|
||||
assert!(f.contains("tcp.SrcPort < 44000 or tcp.SrcPort > 47999"), "{f}");
|
||||
assert!(f.starts_with("not tcp or "));
|
||||
assert!(CUTOFF_PORTS.1 < 49152, "inside Windows' dynamic port range");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -293,25 +293,29 @@ fn auto_proxy_never_routes_what_it_excludes() {
|
||||
#[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"));
|
||||
let (direct, proxy, cutoff) = (dir.join("direct.json"), dir.join("proxy.json"), dir.join("cutoff.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 cut = ps_core::zapret2::cutoff_rules("16509\n", "", "16509\t3.5.0.0/16\n16509\t2600:1f00::/32\n");
|
||||
std::fs::write(&cutoff, serde_json::to_vec(&cut).unwrap()).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());
|
||||
e.zapret2_cutoff_rule_set = Some(cutoff.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 - 3], json!({ "rule_set": ["zapret-unfixable"], "outbound": "proxy" }));
|
||||
assert_eq!(rules[n - 2], json!({ "rule_set": ["zapret-cutoff"], "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"]);
|
||||
assert_eq!(tags(&render_with(&state)), ["zapret-unfixable", "zapret-cutoff"]);
|
||||
state.route_mode = Some(RouteMode::AllBypass);
|
||||
assert!(tags(&render_with(&state)).is_empty());
|
||||
}
|
||||
@@ -135,6 +135,19 @@ enum ZapretVerb {
|
||||
Preset { name: String },
|
||||
/// Which game traffic to handle: all, tcp, udp or null.
|
||||
GameFilter { filter: String },
|
||||
/// zapret2's 16 KB cutoff probe: the networks this line cuts off, and the names that get
|
||||
/// through (status), or probe the line now (probe).
|
||||
Cutoff {
|
||||
#[command(subcommand)]
|
||||
verb: Option<CutoffVerb>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum CutoffVerb {
|
||||
Status,
|
||||
/// Probe the line now: a few minutes, thousands of short direct connections.
|
||||
Probe,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
@@ -668,8 +681,60 @@ async fn auto(ctl: &Ctl, verb: Option<AutoVerb>) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The cutoff probe's findings, as upstream's `proxy-ctl zapret cutoff` prints them.
|
||||
fn print_cutoff(r: &Value) {
|
||||
if let Some(n) = r["note"].as_str().filter(|n| !n.is_empty()) {
|
||||
println!("Note: {n}");
|
||||
}
|
||||
let Some(ts) = r["probed"].as_u64() else {
|
||||
println!("Not probed yet.");
|
||||
return;
|
||||
};
|
||||
println!("Probed: {} from {}", ps_client::utc(ts), r["egress"].as_str().unwrap_or("?"));
|
||||
let nets = r["networks"].as_array().cloned().unwrap_or_default();
|
||||
if nets.is_empty() {
|
||||
println!("Cutoff: none on this line");
|
||||
return;
|
||||
}
|
||||
println!("Cutoff: {} network(s)", nets.len());
|
||||
let fallback = if r["proxyFallback"] == true { "no name - proxy fallback" } else { "no name" };
|
||||
for n in nets {
|
||||
println!(" AS{:<8} {}", n["asn"].as_str().unwrap_or("?"), n["name"].as_str().unwrap_or(fallback));
|
||||
}
|
||||
}
|
||||
|
||||
async fn cutoff(ctl: &Ctl, verb: Option<CutoffVerb>) -> Result<()> {
|
||||
let probe = matches!(verb, Some(CutoffVerb::Probe));
|
||||
let mut r = ctl.call(Request::ZapretCutoff { probe }).await?;
|
||||
if probe {
|
||||
if !ctl.json {
|
||||
println!("Probing this line; this takes a few minutes...");
|
||||
}
|
||||
// Until the round it asked for has begun and ended.
|
||||
let mut began = false;
|
||||
for _ in 0..1800 {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||
r = ctl.call(Request::ZapretCutoff { probe: false }).await?;
|
||||
let probing = r["probing"] == true;
|
||||
began |= probing;
|
||||
if began && !probing || !began && r["note"].as_str().is_some_and(|n| !n.is_empty() && !n.starts_with("probed")) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ctl.json {
|
||||
ctl.print(&r);
|
||||
} else if r["enabled"] != true {
|
||||
println!("The cutoff probe needs zapret.engine = \"zapret2\" with zapret2.cutoff.enable.");
|
||||
} else {
|
||||
print_cutoff(&r);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn zapret(ctl: &Ctl, verb: Option<ZapretVerb>) -> Result<()> {
|
||||
match verb.unwrap_or(ZapretVerb::Status) {
|
||||
ZapretVerb::Cutoff { verb } => return cutoff(ctl, verb).await,
|
||||
ZapretVerb::Status => {
|
||||
let s = ctl.call(Request::Status).await?;
|
||||
let z = &s["zapret"];
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
//! The DPI bypass: zapret with Flowseal's presets, or zapret2 with its strategies; and the
|
||||
//! sites it handles beside the lists it comes with.
|
||||
//! The DPI bypass: zapret with Flowseal's presets, or zapret2 with its strategies and its 16 KB
|
||||
//! cutoff probe; and the sites it handles beside the lists it comes with.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use gpui_kit::assets::IconName;
|
||||
use gpui_kit::component::button::Button;
|
||||
use gpui_kit::component::input::{Textarea, TextareaState};
|
||||
use gpui_kit::component::radio::RadioGroup;
|
||||
@@ -9,9 +12,10 @@ use gpui_kit::component::switch::Switch;
|
||||
use gpui_kit::component::*;
|
||||
use gpui_kit::*;
|
||||
use ps_client::edits;
|
||||
use ps_ipc::Request;
|
||||
use serde_json::Value;
|
||||
|
||||
use super::widgets::{card, hint, page, state_tag};
|
||||
use super::widgets::{Inactive as _, card, hint, page, state_tag};
|
||||
use crate::model::Model;
|
||||
|
||||
const ENGINES: [(&str, &str); 2] = [("zapret-discord-youtube", "Flowseal's presets (zapret)"), ("zapret2", "zapret2")];
|
||||
@@ -37,6 +41,9 @@ pub struct DpiPage {
|
||||
/// The engine and lists the text areas were last filled from: news from the service
|
||||
/// replaces what the user has not changed, never what they have.
|
||||
shown: (String, String, String),
|
||||
/// The cutoff probe's findings (`zapret-cutoff`), followed while it probes.
|
||||
cutoff: Value,
|
||||
_cutoff_poll: Option<Task<()>>,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
@@ -63,11 +70,100 @@ impl DpiPage {
|
||||
}
|
||||
}),
|
||||
];
|
||||
let mut this = Self { model, preset, presets: Vec::new(), domains, exclude, shown: Default::default(), _subscriptions: subscriptions };
|
||||
let mut this = Self { model, preset, presets: Vec::new(), domains, exclude, shown: Default::default(), cutoff: Value::Null, _cutoff_poll: None, _subscriptions: subscriptions };
|
||||
this.sync(window, cx);
|
||||
this.follow_cutoff(false, cx);
|
||||
this
|
||||
}
|
||||
|
||||
/// The cutoff probe's findings, now and (`probe`: after starting it) every two seconds while
|
||||
/// it probes.
|
||||
fn follow_cutoff(&mut self, probe: bool, cx: &mut Context<Self>) {
|
||||
let bridge = self.model.read(cx).bridge().clone();
|
||||
let model = self.model.clone();
|
||||
self._cutoff_poll = Some(cx.spawn(async move |this, cx| {
|
||||
let mut probe = probe;
|
||||
loop {
|
||||
let r = bridge.call(Request::ZapretCutoff { probe }).await;
|
||||
let failed = probe && r.is_err();
|
||||
probe = false;
|
||||
let probing = r.as_ref().is_ok_and(|v| v["probing"] == true);
|
||||
let alive = this.update(cx, |this, cx| {
|
||||
match r {
|
||||
Ok(v) => this.cutoff = v,
|
||||
Err(e) if failed => model.update(cx, |_, cx| cx.emit(crate::model::Outcome::Failed(format!("The cutoff probe: {e:#}").into()))),
|
||||
Err(_) => {}
|
||||
}
|
||||
cx.notify();
|
||||
});
|
||||
if alive.is_err() || !probing {
|
||||
break;
|
||||
}
|
||||
cx.background_executor().timer(Duration::from_secs(2)).await;
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
/// zapret2's 16 KB cutoff probe: on or off, what it found, probe now.
|
||||
fn cutoff_card(&self, config: &Value, cx: &mut Context<Self>) -> Div {
|
||||
let c = &self.cutoff;
|
||||
let on = config["zapret"]["zapret2"]["cutoff"]["enable"] == true;
|
||||
let probing = c["probing"] == true;
|
||||
let probe = Button::new("cutoff-probe")
|
||||
.small()
|
||||
.icon(IconName::Gauge)
|
||||
.label(if probing { "Probing…" } else { "Probe now" })
|
||||
.inactive(probing || !on, cx)
|
||||
.on_click(cx.listener(|this, _, _, cx| this.follow_cutoff(true, cx)));
|
||||
let mut card = card("16 KB cutoff", Some(probe.into_any_element()), cx)
|
||||
.child(hint(
|
||||
"Some lines cut TLS to certain hosting networks after about 16 KB, which no strategy fixes. A probe finds them daily (and when the line's network changes) and, with z2k's strategies, a name that gets through for each, which z2k puts into a fake hello. Each probe makes thousands of short direct connections.",
|
||||
cx,
|
||||
))
|
||||
.child(self.option_switch("cutoff-on", "Probe this line", &["zapret", "zapret2", "cutoff", "enable"], config))
|
||||
.child(self.option_switch(
|
||||
"cutoff-fallback",
|
||||
"Send what no name fixes through the proxy (it sees addresses: the TUN, per-app routing)",
|
||||
&["zapret", "zapret2", "cutoff", "proxyFallback"],
|
||||
config,
|
||||
));
|
||||
if !on || c.is_null() {
|
||||
return card;
|
||||
}
|
||||
if c["installed"] != true {
|
||||
return card.child(hint("z2k-detect, the probe, is not installed (the zapret2-extras component).", cx));
|
||||
}
|
||||
if let Some(n) = c["note"].as_str().filter(|n| !n.is_empty() && (probing || !n.starts_with("probed"))) {
|
||||
card = card.child(hint(n.to_owned(), cx));
|
||||
}
|
||||
let Some(ts) = c["probed"].as_u64() else {
|
||||
return card.child(hint("Not probed yet: the first probe runs five minutes after the service starts.", cx));
|
||||
};
|
||||
let nets = c["networks"].as_array().cloned().unwrap_or_default();
|
||||
let named = nets.iter().filter(|n| n["name"].is_string()).count();
|
||||
let summary = match nets.len() {
|
||||
0 => format!("Probed {} from {}: no network is cut off on this line.", ps_client::utc(ts), c["egress"].as_str().unwrap_or("?")),
|
||||
n => format!("Probed {} from {}: {n} network(s) cut off, {named} with a name that gets through.", ps_client::utc(ts), c["egress"].as_str().unwrap_or("?")),
|
||||
};
|
||||
card = card.child(div().text_sm().child(summary));
|
||||
let fallback = if c["proxyFallback"] == true { "through the proxy" } else { "no name" };
|
||||
const SHOWN: usize = 8;
|
||||
for n in nets.iter().take(SHOWN) {
|
||||
card = card.child(
|
||||
div()
|
||||
.h_flex()
|
||||
.gap_2()
|
||||
.text_sm()
|
||||
.child(div().w(px(110.)).font_family("monospace").text_color(cx.theme().muted_foreground).child(format!("AS{}", n["asn"].as_str().unwrap_or("?"))))
|
||||
.child(n["name"].as_str().unwrap_or(fallback).to_owned()),
|
||||
);
|
||||
}
|
||||
if nets.len() > SHOWN {
|
||||
card = card.child(hint(format!("and {} more (proxy-ctl zapret cutoff).", nets.len() - SHOWN), cx));
|
||||
}
|
||||
card
|
||||
}
|
||||
|
||||
fn engine(config: &Value) -> String {
|
||||
config["zapret"]["engine"].as_str().unwrap_or("zapret-discord-youtube").to_owned()
|
||||
}
|
||||
@@ -222,6 +318,7 @@ impl Render for DpiPage {
|
||||
.child(self.option_switch("ipv6", "IPv6 too", &["zapret", "zapret2", "ipv6"], &config))
|
||||
.child(self.option_switch("strategy-log", "Log the strategy each site gets", &["zapret", "zapret2", "strategyLog"], &config)),
|
||||
);
|
||||
body = body.child(self.cutoff_card(&config, cx));
|
||||
} else {
|
||||
let model = self.model.clone();
|
||||
let filter = config["zapret"]["zapret-discord-youtube"]["gameFilter"].as_str().unwrap_or("null");
|
||||
|
||||
@@ -102,6 +102,12 @@ pub enum Request {
|
||||
AwgSet { name: String, on: bool },
|
||||
/// The last lines of a system-wide profile's tunnel log. Secrets scope, as logs are.
|
||||
AwgLog { name: String, lines: usize },
|
||||
/// The 16 KB cutoff probe: the networks this line cuts, and the names that get through;
|
||||
/// `probe` runs it now.
|
||||
ZapretCutoff {
|
||||
#[serde(default)]
|
||||
probe: bool,
|
||||
},
|
||||
/// This version, and the newest release if it is newer.
|
||||
UpdateCheck,
|
||||
/// Fetches the newest release's setup program, checks it, and runs it: the service stops,
|
||||
|
||||
@@ -140,6 +140,7 @@ fn scope_of(req: &Request) -> Option<Scope> {
|
||||
Request::AutoList | Request::AutoProbe { .. } | Request::AutoLearn { .. } | Request::AutoForget { .. } => Some(Scope::AutoProxy),
|
||||
Request::AwgList | Request::AwgSet { .. } => Some(Scope::AmneziaWg),
|
||||
Request::AwgLog { .. } => Some(Scope::Secrets),
|
||||
Request::ZapretCutoff { .. } => Some(Scope::Zapret),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -674,6 +675,17 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
|
||||
Response::ok(json!({ "lines": crate::awgvpn::log_tail(s.paths(), &vpn.iface, lines.min(2000)) }))
|
||||
}
|
||||
|
||||
Request::ZapretCutoff { probe } => {
|
||||
let s = shared.lock().await;
|
||||
if probe {
|
||||
if !crate::cutoff::enabled(s.cfg()) {
|
||||
return Response::err("the cutoff probe needs zapret.engine = \"zapret2\" with zapret2.cutoff.enable");
|
||||
}
|
||||
crate::cutoff::request_probe();
|
||||
}
|
||||
Response::ok(crate::cutoff::status(s.cfg(), s.paths()))
|
||||
}
|
||||
|
||||
Request::UpdateCheck => {
|
||||
let routes = shared.lock().await.fetch_routes(true);
|
||||
match crate::update::check(&routes).await {
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
//! The 16 KB cutoff probe (upstream's zapret2/cutoff.nix and cutoff-probe.template.sh). Some
|
||||
//! lines let TLS to certain hosting networks shake hands and then kill the connection at
|
||||
//! 12-34 KB, which no strategy fixes. z2k-detect finds which networks (AS) this line cuts and,
|
||||
//! for z2k's own strategies, a whitelisted name per network that z2k's tcp16 Lua puts into a
|
||||
//! fake ClientHello; the networks no name fixes go to a rule-set the proxy carries.
|
||||
//!
|
||||
//! The probe measures the line itself: its connections leave from
|
||||
//! ps_core::zapret2::CUTOFF_PORTS, which winws2 leaves alone, and directly under the TUN.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use ps_core::config::{Config, StrategySource, ZapretEngine};
|
||||
use serde_json::{Value, json};
|
||||
use tokio::sync::Notify;
|
||||
|
||||
use crate::fetch::{self, Route};
|
||||
use crate::paths::Paths;
|
||||
|
||||
/// A day, as upstream's: the maps belong to the line, probed again when its network changes.
|
||||
const MAX_AGE: u64 = 86400;
|
||||
|
||||
static FORCE: Notify = Notify::const_new();
|
||||
|
||||
/// What the probe is doing, and what the last round said.
|
||||
static NOTE: Mutex<(bool, String)> = Mutex::new((false, String::new()));
|
||||
|
||||
fn note(probing: bool, text: impl Into<String>) {
|
||||
let text = text.into();
|
||||
if !text.is_empty() {
|
||||
tracing::info!("cutoff: {text}");
|
||||
}
|
||||
*NOTE.lock().unwrap_or_else(|e| e.into_inner()) = (probing, text);
|
||||
}
|
||||
|
||||
pub fn dir(paths: &Paths) -> PathBuf {
|
||||
paths.root.join("zapret2-cutoff")
|
||||
}
|
||||
|
||||
pub fn enabled(cfg: &Config) -> bool {
|
||||
cfg.enable && cfg.zapret.enable && cfg.zapret.engine == ZapretEngine::Zapret2 && cfg.zapret.zapret2.cutoff.enable
|
||||
}
|
||||
|
||||
/// Whether a name found fixes anything: only z2k's own profiles put it in (z2k-tcp16.lua).
|
||||
/// Elsewhere every cut-off network goes to the proxy, and no name is searched for.
|
||||
pub fn names_apply(cfg: &Config) -> bool {
|
||||
enabled(cfg) && cfg.zapret.zapret2.strategy_source == StrategySource::Z2k && cfg.zapret.zapret2.profiles.is_none()
|
||||
}
|
||||
|
||||
fn extras(paths: &Paths) -> PathBuf {
|
||||
paths.bin().join("zapret2-extras")
|
||||
}
|
||||
|
||||
pub fn program(paths: &Paths) -> Option<PathBuf> {
|
||||
let p = extras(paths).join(if cfg!(windows) { "z2k-detect.exe" } else { "z2k-detect" });
|
||||
p.is_file().then_some(p)
|
||||
}
|
||||
|
||||
fn lists(paths: &Paths) -> PathBuf {
|
||||
extras(paths).join("z2k").join("files").join("lists")
|
||||
}
|
||||
|
||||
/// The rule-set the proxy carries, when it is to (`cutoff.proxyFallback`).
|
||||
pub fn rule_set_path(cfg: &Config, paths: &Paths) -> Option<String> {
|
||||
(enabled(cfg) && cfg.zapret.zapret2.cutoff.proxy_fallback).then(|| dir(paths).join("proxy.json").to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> String {
|
||||
std::fs::read_to_string(path).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What z2k's tcp16 Lua reads inside winws2 (upstream's runtime.nix), with `lua_path` giving
|
||||
/// paths as winws2 opens them; and a digest of the maps, so a new one restarts winws2 (it
|
||||
/// reads them once).
|
||||
pub fn lua_env(cfg: &Config, paths: &Paths, lua_path: impl Fn(&Path) -> String) -> Vec<(String, String)> {
|
||||
if !names_apply(cfg) {
|
||||
return Vec::new();
|
||||
}
|
||||
let d = dir(paths);
|
||||
let digest = {
|
||||
use sha2::{Digest, Sha256};
|
||||
let mut h = Sha256::new();
|
||||
h.update(read(&d.join("asn.txt")));
|
||||
h.update(b"\0");
|
||||
h.update(read(&d.join("sni.txt")));
|
||||
h.finalize().iter().take(8).map(|b| format!("{b:02x}")).collect::<String>()
|
||||
};
|
||||
vec![
|
||||
("Z2K_TCP16_ASN".into(), lua_path(&d.join("asn.txt"))),
|
||||
("Z2K_TCP16_SNI".into(), lua_path(&d.join("sni.txt"))),
|
||||
("Z2K_SNI_PIN".into(), lua_path(&d.join("pin.txt"))),
|
||||
("Z2K_TCP16_NETS".into(), lua_path(&lists(paths).join("tcp16_nets.txt"))),
|
||||
("PROXY_SUITE_CUTOFF_MAPS".into(), digest),
|
||||
]
|
||||
}
|
||||
|
||||
/// The rule-set from the maps as they stand, written only when it changed (sing-box reloads a
|
||||
/// rule-set file replaced). Whether it did.
|
||||
pub fn write_rules(cfg: &Config, paths: &Paths) -> Result<bool> {
|
||||
let Some(path) = rule_set_path(cfg, paths) else { return Ok(false) };
|
||||
let d = dir(paths);
|
||||
std::fs::create_dir_all(&d)?;
|
||||
// Names no profile puts in fix nothing: every cut-off network goes to the proxy.
|
||||
let sni = if names_apply(cfg) { read(&d.join("sni.txt")) } else { String::new() };
|
||||
let rules = ps_core::zapret2::cutoff_rules(&read(&d.join("asn.txt")), &sni, &read(&lists(paths).join("tcp16_nets.txt")));
|
||||
let text = serde_json::to_vec(&rules)?;
|
||||
if std::fs::read(&path).is_ok_and(|old| old == text) {
|
||||
return Ok(false);
|
||||
}
|
||||
crate::paths::write_atomic(Path::new(&path), &text).with_context(|| format!("writing {path}"))?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The probe's maps and when it ran, for `proxy-ctl zapret cutoff` and the app.
|
||||
pub fn status(cfg: &Config, paths: &Paths) -> Value {
|
||||
let d = dir(paths);
|
||||
let names = ps_core::zapret2::network_names(&read(&d.join("sni.txt")));
|
||||
let networks: Vec<Value> = ps_core::zapret2::cut_networks(&read(&d.join("asn.txt")))
|
||||
.into_iter()
|
||||
.map(|asn| {
|
||||
let name = names.get(&asn).filter(|n| !n.is_empty() && names_apply(cfg));
|
||||
json!({ "asn": asn, "name": name })
|
||||
})
|
||||
.collect();
|
||||
let (probing, note) = NOTE.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
json!({
|
||||
"enabled": enabled(cfg),
|
||||
"installed": program(paths).is_some(),
|
||||
"namesApply": names_apply(cfg),
|
||||
"proxyFallback": cfg.zapret.zapret2.cutoff.proxy_fallback,
|
||||
"probing": probing,
|
||||
"note": note,
|
||||
"probed": read(&d.join("ts")).trim().parse::<u64>().ok(),
|
||||
"egress": Some(read(&d.join("egress")).trim().to_owned()).filter(|e| !e.is_empty()),
|
||||
"networks": networks,
|
||||
})
|
||||
}
|
||||
|
||||
/// Probe now, whatever the line and the last probe's age. Under way from now on, for whoever
|
||||
/// follows it: every forced round ends with a note that it is not.
|
||||
pub fn request_probe() {
|
||||
note(true, "about to probe the line");
|
||||
FORCE.notify_one();
|
||||
}
|
||||
|
||||
/// Rounds as upstream's timer runs them: 5 minutes after start, then every 10 (cheap unless
|
||||
/// the line's network changed or a day passed), and at once when asked.
|
||||
pub async fn runner(shared: crate::service::Shared) {
|
||||
let mut wait = Duration::from_secs(300);
|
||||
loop {
|
||||
let force = tokio::select! {
|
||||
_ = tokio::time::sleep(wait) => false,
|
||||
_ = FORCE.notified() => true,
|
||||
};
|
||||
wait = Duration::from_secs(600);
|
||||
if let Err(e) = round(&shared, force).await {
|
||||
note(false, format!("{e:#}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The line's network (`AS…`) as one service names it, or none.
|
||||
async fn asn_from(url: &str, pick: impl Fn(&Value) -> Option<String>) -> Option<String> {
|
||||
let body = tokio::time::timeout(Duration::from_secs(10), fetch::get(url, &Route::Direct, 64 * 1024)).await.ok()?.ok()?;
|
||||
let v: Value = serde_json::from_slice(&body).ok()?;
|
||||
pick(&v).filter(|a| a.len() > 2 && a.starts_with("AS") && a[2..].bytes().all(|b| b.is_ascii_digit()))
|
||||
}
|
||||
|
||||
/// This line's network: two services must agree, as one alone now and then names another
|
||||
/// (each flip cost a full probe). One answer alone counts for the network already known, or
|
||||
/// when none is. Err with why not to probe.
|
||||
async fn egress(known: &str) -> Result<String, String> {
|
||||
let (ipinfo, ifconfig) = tokio::join!(
|
||||
asn_from("https://ipinfo.io/json", |v| v["org"].as_str().and_then(|o| o.split(' ').next()).map(str::to_owned)),
|
||||
asn_from("https://ifconfig.co/json", |v| v["asn"].as_str().map(str::to_owned)),
|
||||
);
|
||||
match (ipinfo, ifconfig) {
|
||||
(Some(a), Some(b)) if a != b => Err(format!("ipinfo.io says {a}, ifconfig.co says {b}; keeping the last probe")),
|
||||
(Some(a), Some(_)) => Ok(a),
|
||||
(None, None) => Err("no answer about this line's network; not probing".into()),
|
||||
(Some(a), None) | (None, Some(a)) => {
|
||||
if !known.is_empty() && a != known {
|
||||
Err(format!("only one service answered, with {a} for this line's {known}; keeping the last probe"))
|
||||
} else {
|
||||
Ok(a)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// z2k-detect with `args`, from the probe's ports, its output appended to the probe's log:
|
||||
/// its exit code.
|
||||
async fn detect(program: &Path, args: &[&str], dir: &Path) -> Result<i32> {
|
||||
let log = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("probe.log"))?;
|
||||
let (lo, hi) = ps_core::zapret2::CUTOFF_PORTS;
|
||||
let mut cmd = tokio::process::Command::new(program);
|
||||
cmd.args(args)
|
||||
.env("Z2K_TCP16_LOCAL_PORTS", format!("{lo}-{hi}"))
|
||||
.current_dir(dir)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(log.try_clone()?)
|
||||
.stderr(log)
|
||||
.kill_on_drop(true);
|
||||
#[cfg(windows)]
|
||||
cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
|
||||
let status = cmd.status().await.with_context(|| format!("running {}", program.display()))?;
|
||||
Ok(status.code().unwrap_or(-1))
|
||||
}
|
||||
|
||||
async fn round(shared: &crate::service::Shared, force: bool) -> Result<()> {
|
||||
let (cfg, paths) = {
|
||||
let s = shared.lock().await;
|
||||
(s.cfg().clone(), s.paths().clone())
|
||||
};
|
||||
if !enabled(&cfg) {
|
||||
if force {
|
||||
note(false, "the cutoff probe is off (zapret.zapret2.cutoff.enable, with the zapret2 engine)");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let Some(program) = program(&paths) else {
|
||||
note(false, "z2k-detect is not installed (the zapret2-extras component)");
|
||||
return Ok(());
|
||||
};
|
||||
let d = dir(&paths);
|
||||
std::fs::create_dir_all(&d)?;
|
||||
let names = names_apply(&cfg);
|
||||
// Names no profile puts in fix nothing: none kept from when one did.
|
||||
if !names && !read(&d.join("sni.txt")).is_empty() {
|
||||
std::fs::write(d.join("sni.txt"), b"")?;
|
||||
}
|
||||
if write_rules(&cfg, &paths)? {
|
||||
tracing::info!("cutoff: the proxy's rule-set follows the maps");
|
||||
}
|
||||
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
|
||||
let last: u64 = read(&d.join("ts")).trim().parse().unwrap_or(0);
|
||||
let known = read(&d.join("egress")).trim().to_owned();
|
||||
let egress = match egress(&known).await {
|
||||
Ok(e) => e,
|
||||
Err(why) => {
|
||||
note(false, why);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
if !force && egress == known && now.saturating_sub(last) < MAX_AGE {
|
||||
return Ok(());
|
||||
}
|
||||
let targets = lists(&paths).join("tcp16_targets.txt");
|
||||
let candidates = lists(&paths).join("sni_wl_candidates.txt");
|
||||
// z2k-detect exits 1 for "cut" and for a file it cannot read alike.
|
||||
if !targets.is_file() || !candidates.is_file() {
|
||||
note(false, "z2k's target lists are missing (the zapret2-extras component)");
|
||||
return Ok(());
|
||||
}
|
||||
note(true, format!("probing the line from {egress}"));
|
||||
let _ = std::fs::write(d.join("probe.log"), b"");
|
||||
let (asn_new, sni_new) = (d.join("asn.new"), d.join("sni.new"));
|
||||
let _ = std::fs::remove_file(&asn_new);
|
||||
let _ = std::fs::remove_file(&sni_new);
|
||||
let t = targets.to_string_lossy().into_owned();
|
||||
match detect(&program, &["tcp16", "-targets", &t, "-parallel", "50", "-asn-out", "asn.new"], &d).await? {
|
||||
1 => {
|
||||
if names {
|
||||
let c = candidates.to_string_lossy().into_owned();
|
||||
let rc = detect(&program, &["tcp16", "-targets", &t, "-scan", &c, "-per-asn", "-batch", "5", "-parallel", "50", "-sni-out", "sni.new"], &d).await?;
|
||||
// 2: no network took any name; the cut-off networks still stand.
|
||||
if rc != 0 && rc != 2 {
|
||||
let _ = std::fs::remove_file(&asn_new);
|
||||
note(false, format!("the name search failed ({rc}); keeping the previous maps (its log: {})", d.join("probe.log").display()));
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if !sni_new.exists() {
|
||||
std::fs::write(&sni_new, b"")?;
|
||||
}
|
||||
}
|
||||
0 => {
|
||||
std::fs::write(&asn_new, b"")?;
|
||||
std::fs::write(&sni_new, b"")?;
|
||||
}
|
||||
rc => {
|
||||
let _ = std::fs::remove_file(&asn_new);
|
||||
note(false, format!("the probe did not run ({rc}); keeping the previous maps (its log: {})", d.join("probe.log").display()));
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let changed = read(&asn_new) != read(&d.join("asn.txt")) || read(&sni_new) != read(&d.join("sni.txt"));
|
||||
std::fs::rename(&asn_new, d.join("asn.txt"))?;
|
||||
std::fs::rename(&sni_new, d.join("sni.txt"))?;
|
||||
write_rules(&cfg, &paths)?;
|
||||
std::fs::write(d.join("egress"), format!("{egress}\n"))?;
|
||||
std::fs::write(d.join("ts"), format!("{now}\n"))?;
|
||||
let cut = ps_core::zapret2::cut_networks(&read(&d.join("asn.txt"))).len();
|
||||
let named = ps_core::zapret2::network_names(&read(&d.join("sni.txt"))).len();
|
||||
note(false, format!("probed from {egress}: {cut} network(s) cut off, {named} with a name"));
|
||||
// winws2 reads the maps once: a new one restarts it (the Lua's environment carries their
|
||||
// digest); what it learned stays on disk.
|
||||
if changed && names {
|
||||
if let Err(e) = shared.lock().await.apply().await {
|
||||
tracing::warn!("cutoff: applying the new maps: {e:#}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -9,6 +9,7 @@ mod awg;
|
||||
mod awgvpn;
|
||||
mod clash;
|
||||
mod components;
|
||||
mod cutoff;
|
||||
mod fetch;
|
||||
mod install;
|
||||
#[cfg(windows)]
|
||||
@@ -124,6 +125,7 @@ pub async fn run(
|
||||
tokio::spawn(autoproxy::sample(shared.clone()));
|
||||
tokio::spawn(autoproxy::sample_slow(shared.clone()));
|
||||
tokio::spawn(zapret::sync_loop(shared.clone()));
|
||||
tokio::spawn(cutoff::runner(shared.clone()));
|
||||
// First fetches: what the configuration needs and has not got yet.
|
||||
{
|
||||
let shared = shared.clone();
|
||||
|
||||
@@ -127,6 +127,16 @@ impl Service {
|
||||
{
|
||||
direct.push(p.to_string_lossy().into_owned());
|
||||
}
|
||||
// The cutoff probe measures the line: its connections, and the service's own lookup of
|
||||
// the line's network, leave directly.
|
||||
if crate::cutoff::enabled(cfg) {
|
||||
if let Some(p) = crate::cutoff::program(paths) {
|
||||
direct.push(p.to_string_lossy().into_owned());
|
||||
}
|
||||
if let Ok(me) = std::env::current_exe() {
|
||||
direct.push(me.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
let (zd, zi) = crate::zapret::direct_sync(cfg, &paths.bin());
|
||||
Env {
|
||||
zapret_direct: ps_core::config::RouteMatch { domains: zd, ips: zi, ..Default::default() },
|
||||
@@ -146,6 +156,7 @@ impl Service {
|
||||
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,
|
||||
zapret2_cutoff_rule_set: crate::cutoff::rule_set_path(cfg, paths),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -392,6 +403,7 @@ impl Service {
|
||||
crate::autoproxy::publish(&rendered.probe_exits, &crate::autoproxy::load(self.paths()))?;
|
||||
}
|
||||
crate::zapret::sync_rule_sets(self.cfg(), self.paths())?;
|
||||
crate::cutoff::write_rules(self.cfg(), self.paths())?;
|
||||
|
||||
let backend = self.cfg().proxy.backend;
|
||||
let main_program = match backend {
|
||||
|
||||
@@ -223,6 +223,10 @@ pub fn zapret2_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<Uni
|
||||
env.push(("Z2K_AUTOCIRCULAR_FALLBACK_OVERRIDE".to_owned(), lua_path(&fallback)));
|
||||
env.push(("PROXY_SUITE_ZAPRET2_VERDICTS".to_owned(), lua_path(&learned.join("verdicts.tsv"))));
|
||||
env.push(("PROXY_SUITE_PUBLIC_SUFFIXES".to_owned(), lua_path(&extras_dir.join("public_suffixes.txt"))));
|
||||
// The 16 KB cutoff probe's maps, for z2k's tcp16 name step (z2k's own strategies).
|
||||
if source.z2k {
|
||||
env.extend(crate::cutoff::lua_env(cfg, paths, lua_path));
|
||||
}
|
||||
}
|
||||
let generation = {
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
@@ -10,4 +10,5 @@ Each has its SHA-256 in the `.sha256` file next to it. SmartScreen may warn of a
|
||||
|
||||
### New
|
||||
- **Updates from the app**: its Overview says when a newer release is out and installs it. The service fetches the setup program from this project's releases, checks its SHA-256 against the one published beside it and runs it silently; the service and the app close for a moment and start again, new, settings kept. Also `proxy-ctl update` and `proxy-ctl update install`. It looks at start and daily (Settings → This app turns that off). This is the first release that has it: from 0.2.0-pre.1, update by running the new setup.
|
||||
- **zapret2's 16 KB cutoff probe** (`zapret2.cutoff`, on by default, as upstream's): some lines cut TLS to certain hosting networks after about 16 KB, which no strategy fixes. z2k's probe finds those networks daily (or when the line's network changes) and, with z2k's strategies, a name that gets through for each, which z2k puts into a fake hello; what no name fixes goes through the proxy, by address (`cutoff.proxyFallback`). The probe's connections leave from ports winws2 leaves alone. On the DPI bypass page, or `proxy-ctl zapret cutoff [probe]`.
|
||||
- **A dark theme**: light, dark, or as Windows is set (the default), in Settings → This app or at the sun/moon in the sidebar; the window's title bar follows it.
|
||||
@@ -12,7 +12,8 @@
|
||||
# learner's arguments), @STALLWATCH@; and the paths, @Z2K@ (z2k's files) and @ROOT@ (the
|
||||
# tree its generator wrote), which winws2 reads where the component is installed.
|
||||
#
|
||||
# tools/build-zapret2-extras.sh OUT_DIR (needs git, bash, gawk, python3, nix)
|
||||
# tools/build-zapret2-extras.sh OUT_DIR (needs git, bash, gawk, python3, nix, go;
|
||||
# Z2K_DETECT_GOOS=linux: z2k-detect for here)
|
||||
set -euo pipefail
|
||||
. "$(dirname "$0")/lib.sh"
|
||||
OUT=$(realpath -m "${1:?output directory}")
|
||||
@@ -46,6 +47,70 @@ if old not in s:
|
||||
open(p, "w").write(s.replace(old, new))
|
||||
PY
|
||||
|
||||
# --- the 16 KB cutoff probe: z2k-detect, as upstream's pkgs/z2k-detect.nix builds it --------
|
||||
# Its connections leave from the local ports the service names (Z2K_TCP16_LOCAL_PORTS), which
|
||||
# winws2's filter leaves out, as upstream's nft rule keeps zapret2 off the probe's cgroup.
|
||||
t=$Z/z2k-detect/internal/tcp16/tcp16.go
|
||||
grep -qF 'raw, err := d.DialContext(ctx, "tcp", addr)' "$t" || { echo "z2k-detect's tcp16 dial changed"; exit 1; }
|
||||
sed -i 's|raw, err := d.DialContext(ctx, "tcp", addr)|raw, err := dialFrom(ctx, \&d, addr)|' "$t"
|
||||
cat >"$Z/z2k-detect/internal/tcp16/localport.go" <<'GO'
|
||||
package tcp16
|
||||
|
||||
// Proxy Suite for Windows: the probe's connections from a range of local ports
|
||||
// (Z2K_TCP16_LOCAL_PORTS, "lo-hi") that the DPI bypass leaves alone. A port taken
|
||||
// (or in TIME_WAIT) is passed over for the next.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
var portLo, portHi = func() (int, int) {
|
||||
lo, hi, ok := strings.Cut(os.Getenv("Z2K_TCP16_LOCAL_PORTS"), "-")
|
||||
a, e1 := strconv.Atoi(lo)
|
||||
b, e2 := strconv.Atoi(hi)
|
||||
if !ok || e1 != nil || e2 != nil || a < 1 || b > 65535 || a > b {
|
||||
return 0, 0
|
||||
}
|
||||
return a, b
|
||||
}()
|
||||
|
||||
var nextPort atomic.Uint32
|
||||
|
||||
func dialFrom(ctx context.Context, d *net.Dialer, addr string) (net.Conn, error) {
|
||||
if portLo == 0 {
|
||||
return d.DialContext(ctx, "tcp", addr)
|
||||
}
|
||||
n := uint32(portHi - portLo + 1)
|
||||
var err error
|
||||
for i := 0; i < 64; i++ {
|
||||
dd := *d
|
||||
dd.LocalAddr = &net.TCPAddr{Port: portLo + int(nextPort.Add(1)%n)}
|
||||
c, e := dd.DialContext(ctx, "tcp", addr)
|
||||
if e == nil {
|
||||
return c, nil
|
||||
}
|
||||
err = e
|
||||
var se *os.SyscallError
|
||||
if !errors.As(e, &se) || se.Syscall != "bind" {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
GO
|
||||
(
|
||||
cd "$Z/z2k-detect"
|
||||
export GOTOOLCHAIN=local GOFLAGS=-mod=mod CGO_ENABLED=0 GOOS=${Z2K_DETECT_GOOS:-windows} GOARCH=amd64
|
||||
ext=; [ "$GOOS" = windows ] && ext=.exe
|
||||
go build -trimpath -ldflags "-s -w" -o "$OUT/z2k-detect$ext" ./cmd/z2k-detect
|
||||
)
|
||||
|
||||
# --- proxy-suite's own Lua --------------------------------------------------------------
|
||||
cp "$UPSTREAM/detect.lua" "$UPSTREAM/persist-every.lua" "$UPSTREAM/strategy-log.lua" "$OUT/lua/"
|
||||
# The suffix list's path from the environment: it is where the component is installed.
|
||||
@@ -191,5 +256,5 @@ for name in NFQWS2_PORTS_TCP NFQWS2_PORTS_UDP; do
|
||||
done >"$OUT/z2k/ports"
|
||||
grep -q '^NFQWS2_PORTS_TCP=.\+' "$OUT/z2k/ports" || { echo "z2k's ports not found"; exit 1; }
|
||||
echo "$Z2K_COMMIT" >"$OUT/z2k/.commit"
|
||||
echo "2026.10.27+z2k.${Z2K_COMMIT:0:7}" >"$OUT/.version"
|
||||
echo "2026.10.28+z2k.${Z2K_COMMIT:0:7}" >"$OUT/.version"
|
||||
echo "zapret2-extras $(cat "$OUT/.version") in $OUT"
|
||||
@@ -6,7 +6,7 @@
|
||||
#
|
||||
# Before the shot, SHOT_STEPS does what it lists, in order, each followed by a moment for the
|
||||
# app to answer: "click:X,Y" (screen points), "type:TEXT" (no spaces), "key:NAME" (xdotool's
|
||||
# names, e.g. ctrl+a), "scroll:X,Y" (ten steps down, there), "wait:SECONDS".
|
||||
# names, e.g. ctrl+a), "scroll:X,Y[,N]" (N steps down, there; ten), "wait:SECONDS".
|
||||
set -euo pipefail
|
||||
OUT=$(realpath -m "${1:?the screenshot, a .png}"); shift
|
||||
WAIT=6
|
||||
@@ -36,7 +36,7 @@ x() { DISPLAY=":$n" "$XDOTOOL/bin/xdotool" "$@"; }
|
||||
for step in ${SHOT_STEPS:-}; do
|
||||
case $step in
|
||||
click:*) p=${step#click:}; x mousemove "${p%,*}" "${p#*,}" click 1 ;;
|
||||
scroll:*) p=${step#scroll:}; x mousemove "${p%,*}" "${p#*,}" click --repeat 10 5 ;;
|
||||
scroll:*) IFS=, read -r sx sy sn <<<"${step#scroll:}"; x mousemove "$sx" "$sy" click --repeat "${sn:-10}" 5 ;;
|
||||
type:*) x type --delay 40 "${step#type:}" ;;
|
||||
key:*) x key "${step#key:}" ;;
|
||||
wait:*) sleep "${step#wait:}" ;;
|
||||
|
||||
Reference in new issue
Block a user