- hostlistRules (zapret-discord-youtube): a group of sites with its own strategy, as upstream's patch-zapret-config.py makes them: the preset's profiles for the rule's family (or another preset's, with configName; Discord's voice profile with it), pointed at the rule's own list with the standard excludes, or the rule's nfqwsArgs; ahead of the preset's own. WinDivert's filter takes the ports they add. Rules with enableDirectSync join the direct list. Names of zapret's own lists, and the instagram/soundcloud/twitter families (not in Flowseal's Windows release), are refused. Every preset with sample rules checked by winws.exe --dry-run (tools/winws-dry-run.sh); one without the profile a rule copies is refused, as upstream refuses it. - The SSH tunnel (sshProxy): Windows' own OpenSSH (System32) as ssh -N -D, with upstream's options and only the configured key offered (IdentitiesOnly: an agent's keys used up the server's tries); the key copied below the protected state root, as Windows' OpenSSH wants it and sing-box's SSH outbound reads it; the server's keys from hostKey, hostKeyFile or knownHostsFile. End to end on Linux against an sshd of the test's own: a page through each, two logins with the copied key. - The dev shell has OpenSSH, for that test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
696 lines
30 KiB
Rust
696 lines
30 KiB
Rust
//! 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, HostlistRule, Zapret, ZapretDefaultDomains, ZapretDefaultIps, ZapretPreset};
|
|
|
|
/// 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()
|
|
}
|
|
|
|
/// A list file's entries: trimmed, without comments and blanks, each once.
|
|
fn list_entries(text: &str) -> Vec<String> {
|
|
let mut seen = BTreeSet::new();
|
|
text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#') && seen.insert(*l)).map(str::to_owned).collect()
|
|
}
|
|
|
|
/// The release's lists a rule's `defaultDomains` and `defaultIps` name, as text.
|
|
pub struct ReleaseLists<'a> {
|
|
pub general: &'a str,
|
|
pub google: &'a str,
|
|
pub ipset_all: &'a str,
|
|
}
|
|
|
|
/// A hostlist rule, worked out as upstream's zapret-domain-groups.nix does: its sites, and what
|
|
/// of which preset its strategy is copied from.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct Rule {
|
|
pub name: String,
|
|
pub domains: Vec<String>,
|
|
pub ips: Vec<String>,
|
|
/// The preset profiles copied for its domains: "general", "google".
|
|
pub families: Vec<&'static str>,
|
|
/// Discord's voice profile copied too (a rule taking another preset, for Discord's sites).
|
|
pub discord_voice: bool,
|
|
pub config_name: Option<String>,
|
|
pub nfqws_args: Vec<String>,
|
|
}
|
|
|
|
/// Instagram's, SoundCloud's and Twitter's lists come with the Linux port upstream uses, not
|
|
/// with Flowseal's Windows release.
|
|
fn not_in_release(rule: &str, list: &str) -> String {
|
|
format!("hostlist rule '{rule}': Flowseal's Windows release has no {list} list")
|
|
}
|
|
|
|
pub fn rule(r: &HostlistRule, lists: &ReleaseLists) -> Result<Rule, String> {
|
|
use ZapretDefaultDomains as D;
|
|
let mut domains = Vec::new();
|
|
let mut families: Vec<&'static str> = Vec::new();
|
|
for group in &r.default_domains {
|
|
let (list, family) = match group {
|
|
D::General | D::Discord => (lists.general, "general"),
|
|
D::Google | D::Youtube => (lists.google, "google"),
|
|
D::Instagram => return Err(not_in_release(&r.name, "instagram")),
|
|
D::Soundcloud => return Err(not_in_release(&r.name, "soundcloud")),
|
|
D::Twitter => return Err(not_in_release(&r.name, "twitter")),
|
|
};
|
|
domains.extend(list_entries(list));
|
|
if !families.contains(&family) {
|
|
families.push(family);
|
|
}
|
|
}
|
|
domains.extend(r.domains.iter().map(|d| d.trim().to_owned()));
|
|
let mut ips = Vec::new();
|
|
for group in &r.default_ips {
|
|
match group {
|
|
ZapretDefaultIps::All => ips.extend(list_entries(lists.ipset_all)),
|
|
}
|
|
}
|
|
ips.extend(r.ips.iter().map(|i| i.trim().to_owned()));
|
|
if let Some(preset) = r.preset {
|
|
families = vec![match preset {
|
|
ZapretPreset::General => "general",
|
|
ZapretPreset::Google => "google",
|
|
ZapretPreset::Instagram => return Err(not_in_release(&r.name, "instagram")),
|
|
ZapretPreset::Soundcloud => return Err(not_in_release(&r.name, "soundcloud")),
|
|
ZapretPreset::Twitter => return Err(not_in_release(&r.name, "twitter")),
|
|
}];
|
|
}
|
|
let once = |v: Vec<String>| {
|
|
let mut seen = BTreeSet::new();
|
|
v.into_iter().filter(|x| !x.is_empty() && seen.insert(x.clone())).collect::<Vec<_>>()
|
|
};
|
|
Ok(Rule {
|
|
name: r.name.clone(),
|
|
domains: once(domains),
|
|
ips: once(ips),
|
|
families,
|
|
discord_voice: r.config_name.is_some() && r.default_domains.iter().any(|g| matches!(g, D::General | D::Discord)),
|
|
config_name: r.config_name.clone(),
|
|
nfqws_args: r.nfqws_args.clone(),
|
|
})
|
|
}
|
|
|
|
/// A rule's own lists, in the lists directory.
|
|
pub fn rule_lists(rule: &Rule) -> (String, String) {
|
|
(format!("list-{}.txt", rule.name), format!("ipset-{}.txt", rule.name))
|
|
}
|
|
|
|
/// A preset's arguments cut into the global ones (the WinDivert filter, `--wf-*`, ahead of the
|
|
/// first profile) and its profiles (between `--new`).
|
|
fn profiles(args: &[String]) -> (Vec<String>, Vec<Vec<String>>) {
|
|
let mut global = Vec::new();
|
|
let mut out = vec![Vec::new()];
|
|
for a in args {
|
|
if a == "--new" {
|
|
out.push(Vec::new());
|
|
} else if out.len() == 1 && out[0].is_empty() && a.starts_with("--wf-") {
|
|
global.push(a.clone());
|
|
} else {
|
|
out.last_mut().unwrap().push(a.clone());
|
|
}
|
|
}
|
|
out.retain(|p| !p.is_empty());
|
|
(global, out)
|
|
}
|
|
|
|
/// `--hostlist=…list-general.txt` and the like: `option` naming one of `files`.
|
|
fn names_list(arg: &str, option: &str, files: &[&str]) -> bool {
|
|
arg.strip_prefix(option).is_some_and(|path| files.contains(&path.rsplit(['\\', '/']).next().unwrap_or(path)))
|
|
}
|
|
|
|
fn family_files(family: &str) -> &'static [&'static str] {
|
|
match family {
|
|
"general" => &["list-general.txt", "list-general-user.txt"],
|
|
_ => &["list-google.txt"],
|
|
}
|
|
}
|
|
|
|
/// A profile pointed at one list of the rule's: its own list arguments (those `drop` says)
|
|
/// gone, the other kind's gone too, the list put in, and the standard excludes there.
|
|
fn retarget(profile: &[String], option: &str, list: &str, drop: impl Fn(&str) -> bool, excludes: &[String]) -> Vec<String> {
|
|
let other = if option == "--hostlist=" { "--ipset=" } else { "--hostlist=" };
|
|
let mut out: Vec<String> = profile.iter().filter(|a| !drop(a) && !a.starts_with(other)).cloned().collect();
|
|
out.push(format!("{option}{list}"));
|
|
for e in excludes {
|
|
if !out.contains(e) {
|
|
out.push(e.clone());
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// The ports a profile filters on, by protocol.
|
|
fn filter_ports<'a>(profile: &'a [String], proto: &str) -> Vec<&'a str> {
|
|
let option = format!("--filter-{proto}=");
|
|
profile.iter().filter_map(|a| a.strip_prefix(option.as_str())).collect()
|
|
}
|
|
|
|
/// The preset's arguments (expanded) with the rules' profiles ahead of its own. `source` gives
|
|
/// another preset's arguments, expanded, for a rule's `configName`; `expand` fills in a rule's
|
|
/// own `nfqwsArgs` as a preset's are. `lists` ends with a separator.
|
|
pub fn with_rules(
|
|
args: Vec<String>,
|
|
rules: &[Rule],
|
|
lists: &str,
|
|
source: &dyn Fn(&str) -> Result<Vec<String>, String>,
|
|
expand: &dyn Fn(&[String]) -> Vec<String>,
|
|
) -> Result<Vec<String>, String> {
|
|
if rules.is_empty() {
|
|
return Ok(args);
|
|
}
|
|
let (mut global, own) = profiles(&args);
|
|
let excludes: Vec<String> = [
|
|
("--hostlist-exclude=", "list-exclude.txt"),
|
|
("--hostlist-exclude=", "list-exclude-user.txt"),
|
|
("--ipset-exclude=", "ipset-exclude.txt"),
|
|
("--ipset-exclude=", "ipset-exclude-user.txt"),
|
|
]
|
|
.iter()
|
|
.map(|(o, f)| format!("{o}{lists}{f}"))
|
|
.collect();
|
|
let mut generated: Vec<Vec<String>> = Vec::new();
|
|
// What WinDivert has to let through for them: their filters' ports, another preset's own.
|
|
let (mut tcp, mut udp): (Vec<String>, Vec<String>) = (Vec::new(), Vec::new());
|
|
for rule in rules {
|
|
let (src_global, src) = match &rule.config_name {
|
|
Some(name) => profiles(&source(name).map_err(|e| format!("hostlist rule '{}': {e}", rule.name))?),
|
|
None => (Vec::new(), own.clone()),
|
|
};
|
|
for a in &src_global {
|
|
if let Some(p) = a.strip_prefix("--wf-tcp=") {
|
|
tcp.push(p.to_owned());
|
|
} else if let Some(p) = a.strip_prefix("--wf-udp=") {
|
|
udp.push(p.to_owned());
|
|
}
|
|
}
|
|
let (list, ipset) = rule_lists(rule);
|
|
let (list, ipset) = (format!("{lists}{list}"), format!("{lists}{ipset}"));
|
|
let missing = |what: &str| format!("hostlist rule '{}': the preset has no {what} profile to copy", rule.name);
|
|
if !rule.domains.is_empty() {
|
|
for family in &rule.families {
|
|
let files = family_files(family);
|
|
let matching: Vec<&Vec<String>> = src.iter().filter(|p| p.iter().any(|a| names_list(a, "--hostlist=", files))).collect();
|
|
if matching.is_empty() {
|
|
return Err(missing(family));
|
|
}
|
|
for p in matching {
|
|
generated.push(retarget(p, "--hostlist=", &list, |a| names_list(a, "--hostlist=", files), &excludes));
|
|
}
|
|
}
|
|
}
|
|
if !rule.ips.is_empty() {
|
|
let matching: Vec<&Vec<String>> = src.iter().filter(|p| p.iter().any(|a| names_list(a, "--ipset=", &["ipset-all.txt"]))).collect();
|
|
if matching.is_empty() {
|
|
return Err(missing("ipset-all"));
|
|
}
|
|
for p in matching {
|
|
generated.push(retarget(p, "--ipset=", &ipset, |a| names_list(a, "--ipset=", &["ipset-all.txt"]), &excludes));
|
|
}
|
|
}
|
|
if rule.discord_voice {
|
|
let voice: Vec<&Vec<String>> = src.iter().filter(|p| p.iter().any(|a| a == "--filter-l7=discord,stun")).collect();
|
|
if voice.is_empty() {
|
|
return Err(missing("Discord voice"));
|
|
}
|
|
generated.extend(voice.into_iter().cloned());
|
|
}
|
|
for fragment in &rule.nfqws_args {
|
|
let args = expand(&cmd_tokens(fragment));
|
|
tcp.extend(filter_ports(&args, "tcp").into_iter().map(str::to_owned));
|
|
udp.extend(filter_ports(&args, "udp").into_iter().map(str::to_owned));
|
|
if !rule.domains.is_empty() {
|
|
generated.push(retarget(&args, "--hostlist=", &list, |a| a.starts_with("--hostlist="), &excludes));
|
|
}
|
|
if !rule.ips.is_empty() {
|
|
generated.push(retarget(&args, "--ipset=", &ipset, |a| a.starts_with("--ipset="), &excludes));
|
|
}
|
|
}
|
|
}
|
|
for (option, extra) in [("--wf-tcp=", &tcp), ("--wf-udp=", &udp)] {
|
|
if extra.is_empty() {
|
|
continue;
|
|
}
|
|
let mut all: Vec<&str> = extra.iter().map(String::as_str).collect();
|
|
match global.iter_mut().find(|a| a.starts_with(option)) {
|
|
Some(a) => {
|
|
let have = a[option.len()..].to_owned();
|
|
all.push(&have);
|
|
*a = format!("{option}{}", crate::zapret2::merge_ports(&all));
|
|
}
|
|
None => global.push(format!("{option}{}", crate::zapret2::merge_ports(&all))),
|
|
}
|
|
}
|
|
let mut out = global;
|
|
for (i, p) in generated.into_iter().chain(own).enumerate() {
|
|
if i > 0 {
|
|
out.push("--new".into());
|
|
}
|
|
out.extend(p);
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
/// 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()));
|
|
// The hostlist rules that ask for it, as upstream's: their sites, their addresses.
|
|
let release = ReleaseLists { general: list_general, google: list_google, ipset_all };
|
|
for r in y.hostlist_rules.iter().filter(|r| r.enable_direct_sync) {
|
|
let Ok(rule) = rule(r, &release) else { continue };
|
|
domains.extend(rule.domains.iter().map(|d| d.trim_start_matches('^').to_owned()));
|
|
if ds.user_ips {
|
|
ips.extend(r.ips.iter().cloned());
|
|
}
|
|
if ds.upstream_ips && r.default_ips.contains(&ZapretDefaultIps::All) {
|
|
ips.extend(parse(ipset_all).into_iter().filter(|i| i != "203.0.113.113/32"));
|
|
}
|
|
}
|
|
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");
|
|
}
|
|
|
|
const FULL: &str = r#"start "zapret" /min "%BIN%winws.exe" --wf-tcp=80,443,%GameFilterTCP% --wf-udp=443,19294-19344,%GameFilterUDP% ^
|
|
--filter-udp=443 --hostlist="%LISTS%list-general.txt" --hostlist="%LISTS%list-general-user.txt" --hostlist-exclude="%LISTS%list-exclude.txt" --dpi-desync=fake --new ^
|
|
--filter-udp=19294-19344 --filter-l7=discord,stun --dpi-desync=fake --new ^
|
|
--filter-tcp=443 --hostlist="%LISTS%list-google.txt" --dpi-desync=multisplit --new ^
|
|
--filter-tcp=80,443 --ipset="%LISTS%ipset-all.txt" --hostlist-exclude="%LISTS%list-exclude.txt" --dpi-desync=fake
|
|
"#;
|
|
const OTHER: &str = r#""%BIN%winws.exe" --wf-tcp=443,2053 --wf-udp=443 --filter-tcp=443,2053 --hostlist="%LISTS%list-general.txt" --dpi-desync=hostfakesplit --new --filter-udp=19294-19344 --filter-l7=discord,stun --dpi-desync=fake"#;
|
|
|
|
fn ex(args: &[String]) -> Vec<String> {
|
|
expand(args, "B\\", "L\\", "R\\", GameFilter::Null)
|
|
}
|
|
|
|
fn lists() -> ReleaseLists<'static> {
|
|
ReleaseLists { general: "discord.com\n# c\n", google: "youtube.com\ngooglevideo.com\n", ipset_all: "203.0.113.0/24\n" }
|
|
}
|
|
|
|
fn rules(json: serde_json::Value) -> Result<Vec<String>, String> {
|
|
let r: HostlistRule = serde_json::from_value(json).unwrap();
|
|
let rule = rule(&r, &lists())?;
|
|
let source = |name: &str| if name == "other" { Ok(ex(&preset_args(OTHER).unwrap())) } else { Err(format!("no preset {name}")) };
|
|
with_rules(ex(&preset_args(FULL).unwrap()), &[rule], "L\\", &source, &ex)
|
|
}
|
|
|
|
fn profile_of(args: &[String], i: usize) -> Vec<String> {
|
|
let (_, p) = profiles(args);
|
|
p[i].clone()
|
|
}
|
|
|
|
#[test]
|
|
fn a_rule_copies_its_family_ahead_of_the_preset() {
|
|
let out = rules(serde_json::json!({ "name": "mine", "domains": ["example.com"], "preset": "general" })).unwrap();
|
|
let first = profile_of(&out, 0);
|
|
assert_eq!(
|
|
first,
|
|
[
|
|
"--filter-udp=443",
|
|
"--hostlist-exclude=L\\list-exclude.txt",
|
|
"--dpi-desync=fake",
|
|
"--hostlist=L\\list-mine.txt",
|
|
"--hostlist-exclude=L\\list-exclude-user.txt",
|
|
"--ipset-exclude=L\\ipset-exclude.txt",
|
|
"--ipset-exclude=L\\ipset-exclude-user.txt",
|
|
]
|
|
);
|
|
// The preset's own follow, untouched; the filter as it was.
|
|
let (global, p) = profiles(&out);
|
|
assert_eq!(p.len(), 5);
|
|
assert_eq!(p[1], profile_of(&ex(&preset_args(FULL).unwrap()), 0));
|
|
assert_eq!(global, ["--wf-tcp=80,443,12", "--wf-udp=443,19294-19344,12"]);
|
|
}
|
|
|
|
#[test]
|
|
fn default_domains_pick_the_list_and_the_family() {
|
|
let r: HostlistRule = serde_json::from_value(serde_json::json!({ "name": "yt", "defaultDomains": ["youtube"], "domains": ["extra.example"] })).unwrap();
|
|
let rule = rule(&r, &lists()).unwrap();
|
|
assert_eq!(rule.domains, ["youtube.com", "googlevideo.com", "extra.example"]);
|
|
assert_eq!(rule.families, ["google"]);
|
|
let out = rules(serde_json::json!({ "name": "yt", "defaultDomains": ["youtube"] })).unwrap();
|
|
assert!(profile_of(&out, 0).contains(&"--dpi-desync=multisplit".to_owned()));
|
|
assert!(profile_of(&out, 0).contains(&"--hostlist=L\\list-yt.txt".to_owned()));
|
|
}
|
|
|
|
#[test]
|
|
fn another_preset_brings_its_ports_and_discord_voice() {
|
|
let out = rules(serde_json::json!({ "name": "d", "defaultDomains": ["discord"], "configName": "other" })).unwrap();
|
|
let (global, p) = profiles(&out);
|
|
assert_eq!(global, ["--wf-tcp=12,80,443,2053", "--wf-udp=12,443,19294-19344"]);
|
|
assert!(p[0].contains(&"--dpi-desync=hostfakesplit".to_owned()));
|
|
assert!(p[1].contains(&"--filter-l7=discord,stun".to_owned()));
|
|
}
|
|
|
|
#[test]
|
|
fn own_args_and_ips() {
|
|
let out = rules(serde_json::json!({ "name": "c", "domains": ["a.example"], "ips": ["198.51.100.0/24"], "nfqwsArgs": ["--filter-tcp=8080 --hostlist=x.txt --dpi-desync=fake"] })).unwrap();
|
|
let (global, p) = profiles(&out);
|
|
assert_eq!(global[0], "--wf-tcp=12,80,443,8080");
|
|
// The ipset-all profile, pointed at the rule's addresses; then its own args, twice.
|
|
assert!(p[0].contains(&"--ipset=L\\ipset-c.txt".to_owned()) && p[0].contains(&"--filter-tcp=80,443".to_owned()));
|
|
assert_eq!(&p[1][..3], ["--filter-tcp=8080", "--dpi-desync=fake", "--hostlist=L\\list-c.txt"]);
|
|
assert!(p[2].contains(&"--ipset=L\\ipset-c.txt".to_owned()) && !p[2].iter().any(|a| a.starts_with("--hostlist=")));
|
|
}
|
|
|
|
#[test]
|
|
fn what_the_windows_release_lacks_is_an_error() {
|
|
assert!(rules(serde_json::json!({ "name": "i", "defaultDomains": ["instagram"] })).unwrap_err().contains("instagram"));
|
|
let err = rules(serde_json::json!({ "name": "g", "domains": ["a.example"], "preset": "google", "configName": "other" })).unwrap_err();
|
|
assert!(err.contains("no google profile"), "{err}");
|
|
}
|
|
|
|
#[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.discord_youtube.hostlist_rules = vec![
|
|
serde_json::from_value(serde_json::json!({ "name": "s", "domains": ["synced.example"], "ips": ["198.51.100.1"], "preset": "general", "enableDirectSync": true })).unwrap(),
|
|
serde_json::from_value(serde_json::json!({ "name": "n", "domains": ["unsynced.example"], "preset": "general", "enableDirectSync": false })).unwrap(),
|
|
];
|
|
let (d, i) = direct_sync(&z, "discord.com\n", "", "", "", "");
|
|
assert_eq!(d, ["discord.com", "mine.example", "synced.example"]);
|
|
assert_eq!(i, ["198.51.100.1"]);
|
|
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);
|
|
}
|
|
}
|