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

@@ -0,0 +1,18 @@
//! For tools/winws-dry-run.sh: a preset's winws arguments as the service builds them, one
//! per line. `zapret_args <release dir> <lists dir> <preset> <game filter>`, paths as
//! Windows sees them (with a trailing separator).
use ps_core::config::GameFilter;
use ps_core::zapret::{expand, find_preset, preset_args};
fn main() {
let a: Vec<String> = std::env::args().collect();
let (release, win_root, win_lists, preset, game) = (&a[1], &a[2], &a[3], &a[4], &a[5]);
let files: Vec<String> = std::fs::read_dir(release).unwrap().filter_map(|e| e.ok()?.file_name().into_string().ok()).collect();
let file = find_preset(&files, preset).unwrap();
let text = std::fs::read_to_string(std::path::Path::new(release).join(file)).unwrap();
let game: GameFilter = serde_json::from_value(serde_json::json!(game)).unwrap();
for arg in expand(&preset_args(&text).unwrap(), &format!("{win_root}bin\\"), win_lists, win_root, game) {
println!("{arg}");
}
}
+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);
}
}
+100
View File
@@ -42,6 +42,34 @@ enum Cmd {
#[command(subcommand)]
verb: ConfigVerb,
},
/// DPI bypass: status, on, off, or the presets and the one to use.
Zapret {
#[command(subcommand)]
verb: Option<ZapretVerb>,
},
/// The backend programs: what is installed, and installing them (administrator).
Components {
#[command(subcommand)]
verb: Option<ComponentsVerb>,
},
}
#[derive(Subcommand)]
enum ZapretVerb {
Status,
On,
Off,
/// Use this preset (zapret-discord-youtube), e.g. "general (ALT9)".
Preset { name: String },
/// Which game traffic to handle: all, tcp, udp or null.
GameFilter { filter: String },
}
#[derive(Subcommand)]
enum ComponentsVerb {
List,
/// Fetch, verify and install (all, or the named).
Install { names: Vec<String> },
}
#[derive(Subcommand)]
@@ -630,6 +658,76 @@ async fn proxy(ctl: &Ctl, verb: Option<ProxyVerb>) -> Result<()> {
Ok(())
}
async fn zapret(ctl: &Ctl, verb: Option<ZapretVerb>) -> Result<()> {
match verb.unwrap_or(ZapretVerb::Status) {
ZapretVerb::Status => {
let s = ctl.call(Request::Status).await?;
let z = &s["zapret"];
if ctl.json {
ctl.print(z);
} else if z["enabled"] == true {
println!("zapret: {} ({}, {})", z["state"].as_str().unwrap_or("?"), z["engine"].as_str().unwrap_or("?"), z["preset"].as_str().unwrap_or("?"));
} else {
println!("zapret: off");
}
}
v @ (ZapretVerb::On | ZapretVerb::Off) => {
let on = matches!(v, ZapretVerb::On);
ctl.edit(|c| {
c["zapret"]["enable"] = on.into();
Ok(())
})
.await?;
}
ZapretVerb::Preset { name } => {
ctl.edit(|c| {
c["zapret"]["zapret-discord-youtube"]["configName"] = name.clone().into();
Ok(())
})
.await?;
}
ZapretVerb::GameFilter { filter } => {
if !matches!(filter.as_str(), "all" | "tcp" | "udp" | "null") {
bail!("the game filter is all, tcp, udp or null");
}
ctl.edit(|c| {
c["zapret"]["zapret-discord-youtube"]["gameFilter"] = filter.clone().into();
Ok(())
})
.await?;
}
}
Ok(())
}
async fn components(ctl: &Ctl, verb: Option<ComponentsVerb>) -> Result<()> {
match verb.unwrap_or(ComponentsVerb::List) {
ComponentsVerb::List => {
let r = ctl.call(Request::Components).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
for c in r.as_array().into_iter().flatten() {
let installed = c["installed"].as_str().unwrap_or("not installed");
let want = c["version"].as_str().unwrap_or("");
let note = if installed == want { "" } else { " (update with proxy-ctl components install)" };
println!("{:14} {:22} installed {installed}{note}", c["name"].as_str().unwrap_or(""), want);
}
}
ComponentsVerb::Install { names } => {
let r = ctl.call(Request::ComponentsInstall { names }).await?;
for c in r.as_array().into_iter().flatten() {
match c["error"].as_str() {
Some(e) => println!("{}: {e}", c["name"].as_str().unwrap_or("")),
None => println!("{} {} installed", c["name"].as_str().unwrap_or(""), c["version"].as_str().unwrap_or("")),
}
}
}
}
Ok(())
}
async fn real_main() -> Result<()> {
let cli = Cli::parse();
let addr = match cli.socket {
@@ -662,6 +760,8 @@ async fn real_main() -> Result<()> {
}
}
Cmd::Proxy(p) => proxy(&ctl, p.verb).await?,
Cmd::Zapret { verb } => zapret(&ctl, verb).await?,
Cmd::Components { verb } => components(&ctl, verb).await?,
Cmd::Config { verb } => match verb {
ConfigVerb::Get => {
let c = ctl.call(Request::ConfigGet).await?;
+16 -1
View File
@@ -160,7 +160,22 @@ pub async fn stage(to: &Path, cache: &Path, only: &[String]) -> Result<()> {
let manifest = ps_core::components::manifest();
std::fs::create_dir_all(to)?;
for (name, comp) in &manifest.components {
if comp.bundled || (!only.is_empty() && !only.contains(name)) {
if !only.is_empty() && !only.contains(name) {
continue;
}
if comp.bundled {
// Built beside this (tools/build-*.sh): recorded as an install records.
let dir = to.join(name);
match installed_version(to, name) {
Some(v) if v == comp.version => {
let mut files = std::collections::BTreeMap::new();
record(&dir, &dir, &mut files)?;
std::fs::write(dir.join(".files.json"), serde_json::to_vec_pretty(&files)?)?;
println!("{name} {} (built)", comp.version);
}
Some(v) => bail!("{name} in {} is {v}, the manifest wants {}", to.display(), comp.version),
None => println!("{name}: not built (tools/build-{name}.sh); left out"),
}
continue;
}
println!("{name} {}", comp.version);
+2
View File
@@ -13,9 +13,11 @@ mod job;
mod paths;
mod service;
mod store;
mod tg;
mod units;
#[cfg(windows)]
mod winsvc;
mod zapret;
use std::path::PathBuf;
use std::sync::Arc;
+77
View File
@@ -36,6 +36,7 @@ pub struct Service {
/// Why the last apply did not take.
pub last_error: Option<String>,
pub last_fetch: BTreeMap<String, SystemTime>,
tcp_timestamps_on: bool,
}
fn digest(data: &[u8]) -> String {
@@ -57,6 +58,7 @@ impl Service {
last: None,
last_error: None,
last_fetch: BTreeMap::new(),
tcp_timestamps_on: false,
store,
})
}
@@ -77,13 +79,22 @@ impl Service {
fn env(&self) -> Env {
let paths = self.paths();
let cfg = self.cfg();
// The helpers' own connections go out directly under the TUN, as upstream's socket
// marks send them: the sidecar's would loop back into sing-box, the relay's too.
let mut direct = Vec::new();
if cfg.proxy.backend == Backend::Hybrid {
if let Ok(x) = self.comps.xray() {
direct.push(x.to_string_lossy().into_owned());
}
}
if cfg.tg_ws_proxy.enable && cfg.tg_ws_proxy.bypass_transparent_proxy {
if let Ok(p) = self.comps.program("tg-ws-proxy", "python/python") {
direct.push(p.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() },
rule_sets: self.store.rule_set_files(),
empty_rule_set: paths.run().join("empty-rule-set.json").to_string_lossy().into_owned(),
cache_dir: paths.cache().to_string_lossy().into_owned(),
@@ -114,6 +125,61 @@ impl Service {
/// Brings the units in line with the configuration: render, write, check, start or
/// restart what changed, stop what is no longer wanted.
pub async fn apply(&mut self) -> Result<()> {
let zapret = self.apply_zapret().await;
if let Err(e) = &zapret {
self.sup.note(crate::zapret::UNIT, format!("proxy-suite: zapret: {e:#}"));
}
let tg = self.apply_tg().await;
if let Err(e) = &tg {
self.sup.note(crate::tg::UNIT, format!("proxy-suite: tg-ws-proxy: {e:#}"));
}
let proxy = self.apply_proxy().await;
zapret.and(tg).and(proxy)
}
async fn apply_tg(&mut self) -> Result<()> {
let cfg = self.cfg().clone();
if !cfg.enable || !cfg.tg_ws_proxy.enable {
self.sup.stop(crate::tg::UNIT).await;
return Ok(());
}
let python = self.comps.program("tg-ws-proxy", "python/python")?;
let spec = crate::tg::unit(&cfg, self.paths(), python)?;
self.sup.ensure(spec);
Ok(())
}
async fn apply_zapret(&mut self) -> Result<()> {
let cfg = self.cfg().clone();
if !cfg.enable || !cfg.zapret.enable {
self.sup.stop(crate::zapret::UNIT).await;
return Ok(());
}
if !cfg!(windows) {
self.sup.note(crate::zapret::UNIT, "proxy-suite: zapret runs on Windows only (WinDivert); not started");
return Ok(());
}
match cfg.zapret.engine {
ps_core::config::ZapretEngine::DiscordYoutube => {
let program = self.comps.program("zapret", "bin/winws")?;
let spec = crate::zapret::discord_youtube_unit(&cfg, self.paths(), program)?;
if cfg.zapret.tcp_timestamps && !self.tcp_timestamps_on {
match crate::zapret::enable_tcp_timestamps().await {
Ok(()) => self.tcp_timestamps_on = true,
Err(e) => self.sup.note(crate::zapret::UNIT, format!("proxy-suite: warning: {e}")),
}
}
self.sup.ensure(spec);
Ok(())
}
ps_core::config::ZapretEngine::Zapret2 => {
self.sup.stop(crate::zapret::UNIT).await;
anyhow::bail!("zapret2 is not supported on Windows yet; use engine \"zapret-discord-youtube\"")
}
}
}
async fn apply_proxy(&mut self) -> Result<()> {
if !self.proxy_wanted() {
self.sup.stop(SOCKS_UNIT).await;
self.sup.stop(SIDECAR_UNIT).await;
@@ -232,6 +298,17 @@ impl Service {
"pinned": self.store.state.pin,
"selection": cfg.proxy.selection.as_str(),
},
"zapret": {
"enabled": cfg.zapret.enable,
"engine": serde_json::to_value(cfg.zapret.engine).unwrap(),
"state": self.sup.state_of(crate::zapret::UNIT).as_str(),
"preset": cfg.zapret.discord_youtube.config_name,
},
"tgWsProxy": {
"enabled": cfg.tg_ws_proxy.enable,
"state": self.sup.state_of(crate::tg::UNIT).as_str(),
"listener": format!("{}:{}", cfg.tg_ws_proxy.listener.address, cfg.tg_ws_proxy.listener.port),
},
"warnings": self.last.as_ref().map(|r| r.warnings.clone()).unwrap_or_default(),
"error": self.last_error,
"revision": self.store.revision,
+104
View File
@@ -0,0 +1,104 @@
//! tg-ws-proxy: Flowseal's Telegram WebSocket bridge, run as upstream's module runs it, on the
//! embedded Python the release carries.
use std::path::PathBuf;
use anyhow::{Context, Result};
use ps_core::config::Config;
use crate::paths::Paths;
use crate::units::UnitSpec;
pub const UNIT: &str = "proxy-suite-tg-ws-proxy";
/// The arguments upstream's module gives it (modules/proxy-suite/tg-ws-proxy.nix).
pub fn args(cfg: &Config, secret: &str) -> Vec<String> {
let t = &cfg.tg_ws_proxy;
let mut a = vec![
"-m".into(),
"proxy.tg_ws_proxy".into(),
format!("--port={}", t.listener.port),
format!("--host={}", t.listener.address),
format!("--secret={secret}"),
];
for (dc, ip) in &t.dc_ips {
a.push(format!("--dc-ip={dc}:{ip}"));
}
if cfg.debug.tg_ws_proxy {
a.push("--verbose".into());
}
if let Some(file) = &t.log.file {
a.push(format!("--log-file={file}"));
a.push(format!("--log-max-mb={}", t.log.max_size_mib));
a.push(format!("--log-backups={}", t.log.keep));
}
a.push(format!("--buf-kb={}", t.buffer_kib));
a.push(format!("--pool-size={}", t.pool_size));
for d in &t.cloudflare.domains {
a.push(format!("--cfproxy-domain={d}"));
}
for d in &t.cloudflare.worker_domains {
a.push(format!("--cfproxy-worker-domain={d}"));
}
if !t.cloudflare.fallback {
a.push("--no-cfproxy".into());
}
if let Some(d) = &t.fake_tls_domain {
a.push(format!("--fake-tls-domain={d}"));
}
if t.proxy_protocol {
a.push("--proxy-protocol".into());
}
a
}
/// The secret: given, or read from `secretFile`, or one generated once and kept.
pub fn secret(cfg: &Config, paths: &Paths) -> Result<String> {
let t = &cfg.tg_ws_proxy;
if let Some(s) = &t.secret {
return Ok(s.clone());
}
if let Some(f) = &t.secret_file {
return Ok(std::fs::read_to_string(f).with_context(|| format!("reading {f}"))?.trim().to_owned());
}
let kept = paths.root.join("tg-ws-proxy.secret");
if let Ok(s) = std::fs::read_to_string(&kept) {
return Ok(s.trim().to_owned());
}
let s: String = (0..32).map(|_| format!("{:x}", rand::random::<u8>() % 16)).collect();
crate::paths::write_atomic(&kept, s.as_bytes())?;
Ok(s)
}
pub fn unit(cfg: &Config, paths: &Paths, python: PathBuf) -> Result<UnitSpec> {
let app = paths.bin().join("tg-ws-proxy").join("app");
let args = args(cfg, &secret(cfg, paths)?);
Ok(UnitSpec {
name: UNIT.into(),
program: python,
generation: args.join("\n"),
args,
// The embedded Python finds its path in its ._pth file; nothing from the
// environment should change it.
env: vec![("PYTHONNOUSERSITE".into(), "1".into()), ("PYTHONDONTWRITEBYTECODE".into(), "1".into())],
cwd: Some(app),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn upstreams_flags() {
let mut cfg = Config::default();
cfg.tg_ws_proxy.dc_ips.insert("2".into(), "149.154.167.220".into());
cfg.tg_ws_proxy.cloudflare.fallback = false;
cfg.tg_ws_proxy.fake_tls_domain = Some("www.example.com".into());
let a = args(&cfg, "ab");
assert_eq!(&a[..5], ["-m", "proxy.tg_ws_proxy", "--port=1443", "--host=127.0.0.1", "--secret=ab"]);
for want in ["--dc-ip=2:149.154.167.220", "--buf-kb=256", "--pool-size=4", "--no-cfproxy", "--fake-tls-domain=www.example.com"] {
assert!(a.contains(&want.to_owned()), "{want} in {a:?}");
}
}
}
+127
View File
@@ -0,0 +1,127 @@
//! 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())?;
}
if !y.hostlist_rules.is_empty() {
tracing::warn!("zapret.zapret-discord-youtube.hostlistRules are not applied on Windows yet");
}
let bin_dir = component.join("bin");
let mut argv = zapret::expand(&args, &with_sep(&bin_dir), &with_sep(&lists), &with_sep(&component), y.game_filter);
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"] {
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(())
}
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
# tg-ws-proxy for Windows: Flowseal's source (the headless proxy, not the tray app) on the
# official embeddable CPython, with its dependencies as pinned win_amd64 wheels. Everything is
# verified: the Python archive and every wheel by hash, the source by its commit.
#
# tools/build-tg-ws-proxy.sh OUT_DIR (needs curl, git, unzip, pip)
set -euo pipefail
cd "$(dirname "$0")"
OUT=${1:?output directory}
PY_VERSION=3.12.10
PY_URL=https://www.python.org/ftp/python/$PY_VERSION/python-$PY_VERSION-embed-amd64.zip
PY_SHA256=4acbed6dd1c744b0376e3b1cf57ce906f9dc9e95e68824584c8099a63025a3c3
TG_TAG=v1.11.2
TG_COMMIT=307a384ab7f522e34bb1a045884d0bd90f40bee5
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
rm -rf "$OUT" && mkdir -p "$OUT/python" "$OUT/app"
curl -sSfL -o "$WORK/python.zip" "$PY_URL"
echo "$PY_SHA256 $WORK/python.zip" | sha256sum -c --quiet
unzip -q "$WORK/python.zip" -d "$OUT/python"
pip download -q --require-hashes --no-deps --only-binary=:all: --platform win_amd64 \
--python-version 3.12 --implementation cp --dest "$WORK/wheels" -r tg-ws-proxy-requirements.txt
mkdir -p "$OUT/python/Lib/site-packages"
for w in "$WORK"/wheels/*.whl; do unzip -q -o "$w" -d "$OUT/python/Lib/site-packages"; done
git clone -q --depth 1 --branch "$TG_TAG" https://github.com/Flowseal/tg-ws-proxy "$WORK/src"
[ "$(git -C "$WORK/src" rev-parse HEAD)" = "$TG_COMMIT" ] || { echo "tag $TG_TAG moved off $TG_COMMIT"; exit 1; }
cp -r "$WORK/src/proxy" "$WORK/src/utils" "$WORK/src/LICENSE" "$OUT/app/"
# The embeddable Python reads its path from this file alone: the standard library, the
# wheels, and the source.
printf 'python312.zip\n.\nLib\\site-packages\n..\\app\nimport site\n' > "$OUT/python/python312._pth"
echo "${TG_TAG#v}+py$PY_VERSION" > "$OUT/.version"
echo "tg-ws-proxy ${TG_TAG#v} on Python $PY_VERSION in $OUT"
@@ -0,0 +1,15 @@
# tg-ws-proxy's dependencies for Windows (win_amd64, CPython 3.12), as wheels, by hash.
# Resolved from its pyproject (httpx[http2]==0.28.1, cryptography==46.0.5, certifi): what proxy/ imports.
anyio==4.15.1 --hash=sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101
certifi==2026.10.23 --hash=sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1
cffi==2.1.1 --hash=sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a
cryptography==46.0.5 --hash=sha256:38946c54b16c885c72c4f59846be9743d699eee2b69b6988e0a00a01f46a61a4
h11==0.16.0 --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86
h2==4.4.1 --hash=sha256:0e25f1462b23c9cb82d9eb02e28bc706dac2a68cb457c6a0d74d63c8a2a5d0e6
hpack==4.2.0 --hash=sha256:858ac0b02280fa582b5080d68db0899c62a80375e0e5413a74970c5e518b6986
httpcore==1.0.9 --hash=sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55
httpx==0.28.1 --hash=sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad
hyperframe==6.1.0 --hash=sha256:b03380493a519fce58ea5af42e4a42317bf9bd425596f7a0835ffce80f1a42e5
idna==3.20 --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c
pycparser==3.12 --hash=sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e
typing-extensions==4.16.0 --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
# Every preset of Flowseal's release, with the arguments and lists the service builds,
# checked by its own winws.exe (`--dry-run`) under Wine.
#
# nix develop --command nix shell nixpkgs#wineWow64Packages.stable -c tools/winws-dry-run.sh STAGE_DIR
set -euo pipefail
cd "$(dirname "$0")/.."
STAGE=${1:?staged components directory}
REL="$STAGE/zapret"
WORK=$(mktemp -d)
export WINEPREFIX=${WINEPREFIX:-$WORK/prefix} WINEDEBUG=-all
trap 'wineserver -k 2>/dev/null || true; rm -rf "$WORK"' EXIT
cargo build -q -p ps-core --example zapret_args
win() { echo "Z:$(realpath "$1" | sed 's|/|\\|g')\\"; }
# The lists as the service writes them: the release's, and the user's placeholders.
mkdir -p "$WORK/lists" && cp "$REL"/lists/*.txt "$WORK/lists/"
echo domain.example.abc > "$WORK/lists/list-general-user.txt"
echo domain.example.abc > "$WORK/lists/list-exclude-user.txt"
echo 203.0.113.113/32 > "$WORK/lists/ipset-exclude-user.txt"
fail=0 n=0
while IFS= read -r preset; do
for game in null all; do
mapfile -t args < <(target/debug/examples/zapret_args "$REL" "$(win "$REL")" "$(win "$WORK/lists")" "$preset" "$game")
n=$((n + 1))
if out=$(cd "$REL/bin" && wine ./winws.exe --dry-run "${args[@]}" 2>&1) && grep -q "parameters verified" <<<"$out"; then
:
else
fail=$((fail + 1)); echo "FAIL: $preset ($game)"; grep -v Cygwin <<<"$out" | tail -4
fi
done
done < <(ls "$REL"/*.bat | xargs -n1 -d '\n' basename | grep -vi '^service' | sed 's/\.bat$//')
echo "$((n - fail))/$n preset runs verified by winws.exe"
[ "$fail" = 0 ]