windows: zapret-discord-youtube and tg-ws-proxy

zapret: Flowseal's release run as its service.bat runs it: the preset's
winws.exe line (continuations, cmd's caret escapes, %BIN%, %LISTS%, the
game filter) as winws's arguments, the user's domains and addresses in
the lists upstream's module puts them in (kept in the service's own run
directory, the verified release untouched), TCP timestamps on, and
zapret's sites in the proxy's direct list. tools/winws-dry-run.sh has
the release's own winws.exe verify every preset's arguments under Wine:
all 22, both game filters.

tg-ws-proxy: Flowseal's headless proxy on the embeddable CPython 3.12
with hash-pinned win_amd64 wheels (tools/build-tg-ws-proxy.sh), run with
upstream's flags; its relay goes direct under the TUN. Runs under Wine.

proxy-ctl: zapret status|on|off|preset|game-filter, components
list|install.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-26 23:55:45 +03:00
1 parent 817de77d28
commit 9b0d7021f9
12 files changed
+873 -1

No files matched your search

+1
View File
@@ -11,3 +11,4 @@ pub mod duration;
pub mod links;
pub mod render;
pub mod wg;
pub mod zapret;
+344
View File
@@ -0,0 +1,344 @@
//! zapret-discord-youtube on Windows: Flowseal's release, run as its `service.bat` would run
//! it, with the user's lists the way upstream's Linux module fills them.
//!
//! A preset is one of the release's `general*.bat` files. Its `winws.exe` command line
//! (continued over `^` lines) is the strategy; `%BIN%`, `%LISTS%` and the game filter's
//! `%GameFilterTCP%` / `%GameFilterUDP%` are filled in. Unlike `service.bat`, which takes the
//! line apart with cmd's FOR (splitting on commas and `=` too) and glues it back, this splits
//! on whitespace alone and hands winws each argument as it was written.
use std::collections::BTreeSet;
use crate::config::{DiscordYoutube, GameFilter, Zapret};
/// What a preset's name is compared by: its letters, digits and brackets, any case.
fn name_key(name: &str) -> String {
name.trim_end_matches(".bat").chars().filter(|c| !c.is_whitespace()).collect::<String>().to_lowercase()
}
/// The release's presets: every `.bat` but `service*.bat`, by name without `.bat`.
pub fn presets(bat_files: &[String]) -> Vec<String> {
let mut names: Vec<String> = bat_files
.iter()
.filter(|f| f.to_lowercase().ends_with(".bat") && !f.to_lowercase().starts_with("service"))
.map(|f| f.trim_end_matches(".bat").trim_end_matches(".BAT").to_owned())
.collect();
// As service.bat lists them: numbers padded, so ALT2 comes before ALT10.
names.sort_by_key(|n| {
let mut key = String::new();
let mut digits = String::new();
for c in n.chars() {
if c.is_ascii_digit() {
digits.push(c);
} else {
if !digits.is_empty() {
key.push_str(&format!("{digits:0>8}"));
digits.clear();
}
key.push(c);
}
}
if !digits.is_empty() {
key.push_str(&format!("{digits:0>8}"));
}
key
});
names
}
/// The file of the preset `config_name` ("general(ALT)" finds "general (ALT).bat").
pub fn find_preset(bat_files: &[String], config_name: &str) -> Result<String, String> {
let want = name_key(config_name);
let found: Vec<&String> = bat_files.iter().filter(|f| f.to_lowercase().ends_with(".bat") && name_key(f) == want).collect();
match found.as_slice() {
[one] => Ok((*one).clone()),
[] => Err(format!(
"zapret preset '{config_name}' is not in this release; it has {}",
presets(bat_files).join(", ")
)),
_ => Err(format!("zapret preset '{config_name}' matches several files")),
}
}
/// cmd's splitting of a command line into arguments: whitespace outside double quotes,
/// quotes kept for now. Outside quotes `^` escapes what follows (`^!` is the `!` that tells
/// winws to use its built-in fake); a `^` before whitespace (a continuation) goes.
fn cmd_tokens(line: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cur = String::new();
let mut quoted = false;
let mut chars = line.chars().peekable();
while let Some(c) = chars.next() {
match c {
'"' => {
quoted = !quoted;
cur.push(c);
}
'^' if !quoted => match chars.peek() {
Some(n) if !n.is_whitespace() => cur.push(chars.next().unwrap()),
_ => {}
},
c if c.is_whitespace() && !quoted => {
if !cur.is_empty() {
out.push(std::mem::take(&mut cur));
}
}
c => cur.push(c),
}
}
if !cur.is_empty() {
out.push(cur);
}
out
}
/// The `winws.exe` arguments of a preset's text, unexpanded.
pub fn preset_args(bat: &str) -> Result<Vec<String>, String> {
let lines: Vec<&str> = bat.lines().collect();
let start = lines
.iter()
.position(|l| l.to_lowercase().contains("winws.exe"))
.ok_or("the preset runs no winws.exe")?;
let mut text = String::new();
for line in &lines[start..] {
let t = line.trim_end();
match t.strip_suffix('^') {
Some(rest) => {
text.push_str(rest);
text.push(' ');
}
None => {
text.push_str(t);
break;
}
}
}
// Everything after the program, quoted or not.
let lower = text.to_lowercase();
let at = lower.find("winws.exe").expect("found above") + "winws.exe".len();
let rest = text[at..].strip_prefix('"').unwrap_or(&text[at..]);
let args = cmd_tokens(rest);
if args.is_empty() {
return Err("the preset gives winws.exe no arguments".into());
}
Ok(args)
}
/// `%GameFilterTCP%` and `%GameFilterUDP%`: the range, or Flowseal's dummy port 12 for off.
pub fn game_filter_ports(filter: GameFilter) -> (&'static str, &'static str) {
const RANGE: &str = "1024-65535";
const OFF: &str = "12";
match filter {
GameFilter::All => (RANGE, RANGE),
GameFilter::Tcp => (RANGE, OFF),
GameFilter::Udp => (OFF, RANGE),
GameFilter::Null => (OFF, OFF),
}
}
/// A preset's arguments with its variables filled in and its quotes gone: `bin` and `lists`
/// end with a path separator, as `%BIN%` and `%LISTS%` do.
pub fn expand(args: &[String], bin: &str, lists: &str, root: &str, game: GameFilter) -> Vec<String> {
let (tcp, udp) = game_filter_ports(game);
args.iter()
.map(|a| {
a.replace("%BIN%", bin)
.replace("%LISTS%", lists)
.replace("%~dp0", root)
.replace("%GameFilterTCP%", tcp)
.replace("%GameFilterUDP%", udp)
.replace('"', "")
})
.collect()
}
/// What the user's lists hold, as files beside the release's: Flowseal's `load_user_lists`
/// placeholders where a list would be empty (winws refuses an empty one).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UserLists {
pub general_user: String,
pub exclude_user: String,
pub ipset_exclude_user: String,
/// Lines appended to the release's `ipset-all.txt`.
pub ipset_all_extra: String,
}
fn lines(items: &[String], placeholder: &str) -> String {
let mut seen = BTreeSet::new();
let mut out = String::new();
for i in items.iter().map(|s| s.trim()).filter(|s| !s.is_empty()) {
if seen.insert(i) {
out.push_str(i);
out.push('\n');
}
}
if out.is_empty() {
out.push_str(placeholder);
out.push('\n');
}
out
}
pub fn user_lists(cfg: &DiscordYoutube, cidr_exemption: &[String]) -> UserLists {
let mut exclude_ips = cfg.exclude_ips.clone();
exclude_ips.extend(cidr_exemption.iter().cloned());
UserLists {
general_user: lines(&cfg.domains, "domain.example.abc"),
exclude_user: lines(&cfg.exclude_domains, "domain.example.abc"),
ipset_exclude_user: lines(&exclude_ips, "203.0.113.113/32"),
ipset_all_extra: cfg.ips.iter().map(|s| format!("{}\n", s.trim())).collect(),
}
}
/// zapret's sites for the proxy's direct list (`zapret.directSync`), from the release's
/// lists and the user's: as upstream's rules-zapret-direct.nix has them. "^name" (an exact
/// match in winws) becomes the plain suffix, which is what a proxy rule can say.
pub fn direct_sync(z: &Zapret, list_general: &str, list_google: &str, list_exclude: &str, ipset_all: &str, ipset_exclude: &str) -> (Vec<String>, Vec<String>) {
let ds = &z.direct_sync;
if !z.enable || !ds.enable {
return (Vec::new(), Vec::new());
}
let parse = |text: &str| -> Vec<String> {
text.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.map(|l| l.trim_start_matches('^').to_owned())
.collect()
};
let y = &z.discord_youtube;
let mut domains: Vec<String> = Vec::new();
let mut ips: Vec<String> = Vec::new();
if z.engine == crate::config::ZapretEngine::DiscordYoutube {
domains.extend(parse(list_general));
domains.extend(parse(list_google));
domains.extend(y.domains.iter().map(|d| d.trim_start_matches('^').to_owned()));
let mut excluded: BTreeSet<String> = parse(list_exclude).into_iter().collect();
excluded.extend(y.exclude_domains.iter().map(|d| d.trim_start_matches('^').to_owned()));
domains.retain(|d| !excluded.contains(d));
if ds.upstream_ips {
// The release's own ipset-all is a placeholder unless loaded; it is what it is.
ips.extend(parse(ipset_all).into_iter().filter(|i| i != "203.0.113.113/32"));
}
if ds.user_ips {
ips.extend(y.ips.iter().cloned());
}
let mut excluded_ips: BTreeSet<String> = BTreeSet::new();
if ds.upstream_ips {
excluded_ips.extend(parse(ipset_exclude));
}
if ds.user_ips {
excluded_ips.extend(y.exclude_ips.iter().cloned());
}
ips.retain(|i| !excluded_ips.contains(i));
} else {
domains.extend(z.zapret2.domains.iter().cloned());
let excluded: BTreeSet<&String> = z.zapret2.exclude_domains.iter().collect();
domains.retain(|d| !excluded.contains(d));
}
let dedup = |v: Vec<String>| {
let mut seen = BTreeSet::new();
v.into_iter().filter(|x| !x.is_empty() && seen.insert(x.clone())).collect::<Vec<_>>()
};
(dedup(domains), dedup(ips))
}
#[cfg(test)]
mod tests {
use super::*;
const ALT: &str = r#"@echo off
chcp 65001 > nul
set "BIN=%~dp0bin\"
set "LISTS=%~dp0lists\"
cd /d %BIN%
start "zapret: %~n0" /min "%BIN%winws.exe" --wf-tcp=80,443,%GameFilterTCP% --wf-udp=443,%GameFilterUDP% ^
--filter-udp=443 --hostlist="%LISTS%list-general.txt" --dpi-desync=fake --dpi-desync-fake-quic="%BIN%quic_initial_www_google_com.bin" --new ^
--filter-tcp=443 --hostlist="%LISTS%list-google.txt" --dpi-desync-fake-tls-mod=rnd,dupsid,sni=www.google.com --dpi-desync-cutoff=n3
"#;
#[test]
fn a_preset_becomes_winws_arguments() {
let args = preset_args(ALT).unwrap();
assert_eq!(args[0], "--wf-tcp=80,443,%GameFilterTCP%");
assert_eq!(args.last().unwrap(), "--dpi-desync-cutoff=n3");
assert!(args.contains(&"--new".to_owned()));
let out = expand(&args, r"C:\z\bin\", r"C:\run\lists\", r"C:\z\", GameFilter::Null);
assert_eq!(out[0], "--wf-tcp=80,443,12");
assert_eq!(out[1], "--wf-udp=443,12");
assert!(out.contains(&r"--hostlist=C:\run\lists\list-general.txt".to_owned()));
assert!(out.contains(&r"--dpi-desync-fake-quic=C:\z\bin\quic_initial_www_google_com.bin".to_owned()));
assert!(out.contains(&"--dpi-desync-fake-tls-mod=rnd,dupsid,sni=www.google.com".to_owned()));
let all = expand(&args, "b\\", "l\\", "r\\", GameFilter::All);
assert_eq!(all[0], "--wf-tcp=80,443,1024-65535");
}
#[test]
fn carets_escape_as_cmd_has_them() {
let args = preset_args("\"%BIN%winws.exe\" --dpi-desync-fake-tls=^! --x=\"a^b\" ^\n--y=^^z").unwrap();
assert_eq!(args, ["--dpi-desync-fake-tls=!", "--x=\"a^b\"", "--y=^z"]);
}
#[test]
fn presets_are_found_by_name_without_spaces() {
let files: Vec<String> = ["general.bat", "general (ALT).bat", "general (ALT10).bat", "general (ALT2).bat", "service.bat"]
.map(String::from)
.to_vec();
assert_eq!(find_preset(&files, "general(ALT)").unwrap(), "general (ALT).bat");
assert_eq!(find_preset(&files, "General (alt2)").unwrap(), "general (ALT2).bat");
assert!(find_preset(&files, "general(ALT99)").unwrap_err().contains("general (ALT2)"));
assert_eq!(presets(&files), ["general", "general (ALT)", "general (ALT2)", "general (ALT10)"]);
}
#[test]
fn user_lists_keep_flowseals_placeholders() {
let mut y = DiscordYoutube::default();
let l = user_lists(&y, &[]);
assert_eq!(l.general_user, "domain.example.abc\n");
assert_eq!(l.ipset_exclude_user, "203.0.113.113/32\n");
y.domains = vec!["a.com".into(), "a.com".into(), "b.com".into()];
y.ips = vec!["198.51.100.0/24".into()];
let l = user_lists(&y, &["192.168.123.0/24".into()]);
assert_eq!(l.general_user, "a.com\nb.com\n");
assert_eq!(l.ipset_all_extra, "198.51.100.0/24\n");
assert_eq!(l.ipset_exclude_user, "192.168.123.0/24\n");
}
#[test]
fn direct_sync_takes_the_lists_minus_the_excludes() {
let mut z = Zapret { enable: true, ..Default::default() };
z.discord_youtube.domains = vec!["mine.example".into()];
z.discord_youtube.exclude_domains = vec!["youtube.com".into()];
let (d, i) = direct_sync(&z, "discord.com\n^dns.google\n# c\nyoutube.com\n", "googlevideo.com\n", "", "203.0.113.113/32\n", "");
assert_eq!(d, ["discord.com", "dns.google", "googlevideo.com", "mine.example"]);
assert!(i.is_empty());
z.direct_sync.enable = false;
assert_eq!(direct_sync(&z, "x.com", "", "", "", "").0, Vec::<String>::new());
}
}
/// Every preset of a real release, when `PS_ZAPRET_RELEASE` names its unpacked directory.
#[cfg(test)]
#[test]
fn every_preset_of_the_release_parses() {
let Ok(dir) = std::env::var("PS_ZAPRET_RELEASE") else { return };
let files: Vec<String> = std::fs::read_dir(&dir)
.unwrap()
.filter_map(|e| e.ok()?.file_name().into_string().ok())
.filter(|f| f.ends_with(".bat"))
.collect();
let names = presets(&files);
assert!(names.len() > 10, "{names:?}");
for name in names {
let file = find_preset(&files, &name).unwrap();
let text = std::fs::read_to_string(std::path::Path::new(&dir).join(&file)).unwrap();
let args = expand(&preset_args(&text).unwrap(), "B\\", "L\\", "R\\", GameFilter::All);
for a in &args {
assert!(a.starts_with("--"), "{name}: {a:?}");
assert!(!a.contains('%') && !a.contains('"'), "{name}: {a:?}");
}
assert!(args.iter().filter(|a| *a == "--new").count() >= 1, "{name}");
assert!(args[0].starts_with("--wf-"), "{name}: {}", args[0]);
println!("{name}: {} args, {} profiles", args.len(), args.iter().filter(|a| *a == "--new").count() + 1);
}
}