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:
faumarayandClaude Opus 5.5 committed 2026-10-27 23:12:43 +03:00
1 parent d33f05c62c
commit 803e18db9d
19 files changed
+721 -18

No files matched your search

+26
View File
@@ -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");
}
+3
View File
@@ -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)
{
+93
View File
@@ -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::*;
+7 -3
View File
@@ -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());
}
+65
View File
@@ -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"];
+101 -4
View File
@@ -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");
+6
View File
@@ -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,
+12
View File
@@ -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 {
+306
View File
@@ -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(())
}
+2
View File
@@ -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();
+12
View File
@@ -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 {
+4
View File
@@ -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};