Files
proxy-suite-flake/windows/crates/ps-service/src/zapret.rs
T
faumarayandClaude Opus 5.5 514ffb97ca 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>
2026-10-27 18:16:48 +03:00

393 lines
17 KiB
Rust

//! zapret on Windows: the unit that runs winws.exe (zapret-discord-youtube) with the
//! configured preset, and the lists it reads.
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use ps_core::config::{Config, ZapretEngine};
use ps_core::zapret;
use crate::paths::{Paths, write_atomic};
use crate::units::UnitSpec;
pub const UNIT: &str = "proxy-suite-zapret";
/// The release's list files, as `zapret::direct_sync` reads them.
pub struct ReleaseLists {
pub general: String,
pub google: String,
pub exclude: String,
pub ipset_all: String,
pub ipset_exclude: String,
}
pub fn release_lists(component: &Path) -> ReleaseLists {
let read = |f: &str| std::fs::read_to_string(component.join("lists").join(f)).unwrap_or_default();
ReleaseLists {
general: read("list-general.txt"),
google: read("list-google.txt"),
exclude: read("list-exclude.txt"),
ipset_all: read("ipset-all.txt"),
ipset_exclude: read("ipset-exclude.txt"),
}
}
/// The domains and addresses `zapret.directSync` sends direct.
pub fn direct_sync(cfg: &Config, bin: &Path) -> (Vec<String>, Vec<String>) {
if !cfg.enable || !cfg.zapret.enable || cfg.zapret.engine != ZapretEngine::DiscordYoutube {
return zapret::direct_sync(&cfg.zapret, "", "", "", "", "");
}
let l = release_lists(&bin.join("zapret"));
zapret::direct_sync(&cfg.zapret, &l.general, &l.google, &l.exclude, &l.ipset_all, &l.ipset_exclude)
}
fn with_sep(p: &Path) -> String {
let s = p.to_string_lossy().into_owned();
let sep = if cfg!(windows) { '\\' } else { '/' };
if s.ends_with(sep) { s } else { format!("{s}{sep}") }
}
/// The unit for zapret-discord-youtube: the preset's winws.exe line, with the lists in the
/// service's run directory (the release's own, the user's entries added) and the game
/// filter. `program` is the verified winws.exe.
pub fn discord_youtube_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<UnitSpec> {
let y = &cfg.zapret.discord_youtube;
let component = paths.bin().join("zapret");
let bats: Vec<String> = std::fs::read_dir(&component)
.with_context(|| format!("reading {}", component.display()))?
.filter_map(|e| e.ok()?.file_name().into_string().ok())
.collect();
let file = zapret::find_preset(&bats, &y.config_name).map_err(anyhow::Error::msg)?;
let bat = std::fs::read(component.join(&file))?;
let args = zapret::preset_args(&String::from_utf8_lossy(&bat)).map_err(anyhow::Error::msg)?;
// The lists: the release's, copied, with the user's beside them.
let lists = paths.run().join("zapret").join("lists");
std::fs::create_dir_all(&lists)?;
let release = component.join("lists");
for entry in std::fs::read_dir(&release)?.flatten() {
let name = entry.file_name();
if name.to_string_lossy().ends_with(".txt") {
std::fs::copy(entry.path(), lists.join(&name))?;
}
}
let exempt: &[String] = if cfg.zapret.cidr_exemption.enable { &cfg.zapret.cidr_exemption.cidrs } else { &[] };
let user = zapret::user_lists(y, exempt);
write_atomic(&lists.join("list-general-user.txt"), user.general_user.as_bytes())?;
write_atomic(&lists.join("list-exclude-user.txt"), user.exclude_user.as_bytes())?;
write_atomic(&lists.join("ipset-exclude-user.txt"), user.ipset_exclude_user.as_bytes())?;
if !user.ipset_all_extra.is_empty() {
let mut all = std::fs::read_to_string(lists.join("ipset-all.txt")).unwrap_or_default();
if !all.ends_with('\n') && !all.is_empty() {
all.push('\n');
}
all.push_str(&user.ipset_all_extra);
write_atomic(&lists.join("ipset-all.txt"), all.as_bytes())?;
}
// The hostlist rules: their sites in their own lists, their profiles ahead of the preset's.
let read = |f: &str| std::fs::read_to_string(release.join(f)).unwrap_or_default();
let (general, google, ipset_all) = (read("list-general.txt"), read("list-google.txt"), read("ipset-all.txt"));
let release_lists = zapret::ReleaseLists { general: &general, google: &google, ipset_all: &ipset_all };
let rules = y.hostlist_rules.iter().map(|r| zapret::rule(r, &release_lists)).collect::<Result<Vec<_>, _>>().map_err(anyhow::Error::msg)?;
let mut rule_files = Vec::new();
for rule in &rules {
let (list, ipset) = zapret::rule_lists(rule);
for (file, entries) in [(list, &rule.domains), (ipset, &rule.ips)] {
if !entries.is_empty() {
write_atomic(&lists.join(&file), format!("{}\n", entries.join("\n")).as_bytes())?;
rule_files.push(file);
}
}
}
let bin_dir = component.join("bin");
let (bin_s, lists_s, root_s) = (with_sep(&bin_dir), with_sep(&lists), with_sep(&component));
let expand = |a: &[String]| zapret::expand(a, &bin_s, &lists_s, &root_s, y.game_filter);
let source = |name: &str| -> Result<Vec<String>, String> {
let file = zapret::find_preset(&bats, name)?;
let bat = std::fs::read(component.join(&file)).map_err(|e| format!("{file}: {e}"))?;
Ok(expand(&zapret::preset_args(&String::from_utf8_lossy(&bat))?))
};
let mut argv = zapret::with_rules(expand(&args), &rules, &lists_s, &source, &expand).map_err(anyhow::Error::msg)?;
if cfg.debug.log_level != ps_core::config::LogLevel::Warn {
argv.insert(0, "--debug=1".into());
}
// A change of the arguments or of a list winws reads is a restart.
let generation = {
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
for a in &argv {
h.update(a.as_bytes());
h.update(b"\n");
}
for f in ["list-general-user.txt", "list-exclude-user.txt", "ipset-exclude-user.txt", "ipset-all.txt"].iter().map(|f| f.to_string()).chain(rule_files) {
h.update(std::fs::read(lists.join(&f)).unwrap_or_default());
}
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
};
Ok(UnitSpec { name: UNIT.into(), program, args: argv, env: Vec::new(), cwd: Some(bin_dir), generation })
}
/// TCP timestamps on, as Flowseal's and bol-van's installers turn them on: strategies that
/// fool DPI with them need them.
pub async fn enable_tcp_timestamps() -> Result<()> {
if !cfg!(windows) {
return Ok(());
}
let status = tokio::process::Command::new("netsh")
.args(["interface", "tcp", "set", "global", "timestamps=enabled"])
.status()
.await
.context("running netsh")?;
if !status.success() {
bail!("netsh could not turn TCP timestamps on");
}
Ok(())
}
/// The unit for zapret2: winws2 with nfqws2-keenetic's or z2k's strategies
/// (ps_core::zapret2), upstream's Lua layers from the zapret2-extras component when it is
/// installed, its lists in the service's `zapret2\\` directory, and what winws2 writes (the
/// learned list, each site's strategy, the detector's verdicts) where it can still write once
/// it runs at Low integrity.
pub fn zapret2_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<UnitSpec> {
use ps_core::config::StrategySource;
use ps_core::zapret2;
let z = &cfg.zapret.zapret2;
let component = paths.bin().join("zapret2");
let extras_dir = paths.bin().join("zapret2-extras");
let extras_there = extras_dir.join("lua").join("detect.lua").is_file();
let keenetic_dir = component.join("keenetic");
let source = if z.strategy_source == StrategySource::Z2k && extras_there {
let z2k = extras_dir.join("z2k");
let read = |name: &str| std::fs::read_to_string(z2k.join(name)).with_context(|| format!("reading z2k's {name}"));
zapret2::z2k(
&read("profiles.plain")?,
&read("profiles.learn")?,
&read("blobs")?,
&read("ports")?,
&lua_path(&z2k),
&lua_path(&z2k.join("root")),
&with_sep_lua(&z2k.join("files").join("lua")),
)
.map_err(anyhow::Error::msg)?
} else {
let conf = std::fs::read_to_string(keenetic_dir.join("nfqws2.conf")).context("reading nfqws2-keenetic's nfqws2.conf")?;
zapret2::keenetic(&conf, &with_sep(&keenetic_dir)).map_err(anyhow::Error::msg)?
};
let state = paths.root.join("zapret2");
let learned = state.join("learned");
let circular = learned.join("circular");
let fallback = learned.join("run");
std::fs::create_dir_all(&circular)?;
std::fs::create_dir_all(&fallback)?;
#[cfg(windows)]
low_integrity(&learned)?;
let user = state.join("zapret-hosts-user.txt");
let exclude = state.join("zapret-hosts-user-exclude.txt");
let auto = learned.join("zapret-hosts-auto.txt");
// nfqws2 refuses a list it cannot open; an empty one is fine.
for f in [&user, &exclude, &auto] {
if !f.exists() {
std::fs::write(f, b"")?;
}
}
let extras = extras_there.then(|| {
// Never learned by the detector, as the source's own learning never learned them.
let mut exclude_lua = Vec::new();
if !source.z2k {
exclude_lua.push(lua_path(&keenetic_dir.join("lists").join("exclude.list")));
}
exclude_lua.push(lua_path(&exclude));
zapret2::Extras {
lua: with_sep(&extras_dir.join("lua")),
z2k_lua: with_sep(&extras_dir.join("z2k").join("files").join("lua")),
auto_lua: lua_path(&auto),
exclude_lua,
}
});
let p = zapret2::Paths {
lua: with_sep(&component.join("lua")),
user: user.to_string_lossy().into_owned(),
exclude: exclude.to_string_lossy().into_owned(),
auto: auto.to_string_lossy().into_owned(),
extras,
};
let argv = zapret2::args(z, &source, &p, cfg.debug.zapret2.packets).map_err(anyhow::Error::msg)?;
// Read inside winws2 by z2k's state layer, the detector and the per-site key.
let mut env = Vec::new();
if extras_there {
env.push(("Z2K_STATE_DIR_OVERRIDE".to_owned(), lua_path(&circular)));
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"))));
}
let generation = {
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
for a in argv.iter().chain(env.iter().map(|(_, v)| v)) {
h.update(a.as_bytes());
h.update(b"\n");
}
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
};
// 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()))?;
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. 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('"', "\\\""));
out.push('"');
} else {
out.push_str(a);
}
out.push('\n');
}
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
/// environment: Cygwin's `/cygdrive/c/…` on Windows (winws2 is a Cygwin program), as it is
/// elsewhere.
fn lua_path(p: &Path) -> String {
let s = p.to_string_lossy().into_owned();
if cfg!(windows) { cygwin(&s) } else { s }
}
fn with_sep_lua(p: &Path) -> String {
let mut s = lua_path(p);
if !s.ends_with('/') && !s.ends_with('\\') {
s.push(if cfg!(windows) { '/' } else { std::path::MAIN_SEPARATOR });
}
s
}
/// `C:\\a\\b` as Cygwin names it: `/cygdrive/c/a/b`.
fn cygwin(path: &str) -> String {
let path = path.trim_start_matches(r"\\?\");
match path.as_bytes() {
[d, b':', rest @ ..] if d.is_ascii_alphabetic() => {
format!("/cygdrive/{}{}", (*d as char).to_ascii_lowercase(), String::from_utf8_lossy(rest).replace('\\', "/"))
}
_ => path.replace('\\', "/"),
}
}
/// A Low mandatory label on `dir`, inherited below it: what a Low-integrity process (winws2,
/// once it runs) may still write to. Its DACL stays as it is.
#[cfg(windows)]
fn low_integrity(dir: &Path) -> Result<()> {
use std::ffi::c_void;
use std::os::windows::ffi::OsStrExt;
use std::ptr::null_mut;
use windows_sys::Win32::Foundation::{ERROR_SUCCESS, LocalFree};
use windows_sys::Win32::Security::Authorization::{
ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1, SE_FILE_OBJECT, SetNamedSecurityInfoW,
};
use windows_sys::Win32::Security::{ACL, GetSecurityDescriptorSacl, LABEL_SECURITY_INFORMATION};
let sddl: Vec<u16> = "S:(ML;OICI;NW;;;LW)".encode_utf16().chain(Some(0)).collect();
let path: Vec<u16> = dir.as_os_str().encode_wide().chain(Some(0)).collect();
let mut sd: *mut c_void = null_mut();
// SAFETY: NUL-terminated inputs; the SACL points into sd, freed below.
unsafe {
if ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.as_ptr(), SDDL_REVISION_1, &mut sd, null_mut()) == 0 {
return Err(std::io::Error::last_os_error().into());
}
let (mut present, mut defaulted) = (0, 0);
let mut sacl: *mut ACL = null_mut();
GetSecurityDescriptorSacl(sd, &mut present, &mut sacl, &mut defaulted);
let rc = SetNamedSecurityInfoW(path.as_ptr() as *mut u16, SE_FILE_OBJECT, LABEL_SECURITY_INFORMATION, null_mut(), null_mut(), null_mut(), sacl);
LocalFree(sd);
if rc != ERROR_SUCCESS {
return Err(std::io::Error::from_raw_os_error(rc as i32).into());
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[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).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]
fn cygwin_names_drives_and_separators() {
assert_eq!(cygwin(r"C:\ProgramData\ProxySuite\zapret2\learned"), "/cygdrive/c/ProgramData/ProxySuite/zapret2/learned");
assert_eq!(cygwin(r"\\?\D:\x"), "/cygdrive/d/x");
}
}