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>
This commit is contained in:
1 parent
9eed225ccc
commit
514ffb97ca
10 files changed
+305
-27
No files matched your search
@@ -108,6 +108,7 @@ pub async fn run(
|
||||
tokio::spawn(autoproxy::runner(shared.clone()));
|
||||
tokio::spawn(autoproxy::sample(shared.clone()));
|
||||
tokio::spawn(autoproxy::sample_slow(shared.clone()));
|
||||
tokio::spawn(zapret::sync_loop(shared.clone()));
|
||||
// First fetches: what the configuration needs and has not got yet.
|
||||
{
|
||||
let shared = shared.clone();
|
||||
|
||||
@@ -144,6 +144,8 @@ impl Service {
|
||||
ssh_host_keys: if cfg.ssh_proxy.enable { crate::ssh::host_keys(cfg, |f| std::fs::read_to_string(f).ok()) } else { Vec::new() },
|
||||
windows: cfg!(windows),
|
||||
autoproxy_rules_dir: cfg.proxy.auto_proxy.enable.then(|| crate::autoproxy::rules_dir(paths).to_string_lossy().into_owned()),
|
||||
zapret2_direct_rule_set: crate::zapret::rule_set_paths(cfg, paths).0,
|
||||
zapret2_proxy_rule_set: crate::zapret::rule_set_paths(cfg, paths).1,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -384,10 +386,12 @@ impl Service {
|
||||
for w in &rendered.warnings {
|
||||
self.sup.note(SOCKS_UNIT, format!("proxy-suite: warning: {w}"));
|
||||
}
|
||||
// sing-box refuses a local rule-set file that is not there: autoProxy's, written first.
|
||||
// sing-box refuses a local rule-set file that is not there: autoProxy's and zapret2's,
|
||||
// written first.
|
||||
if !rendered.probe_exits.is_empty() {
|
||||
crate::autoproxy::publish(&rendered.probe_exits, &crate::autoproxy::load(self.paths()))?;
|
||||
}
|
||||
crate::zapret::sync_rule_sets(self.cfg(), self.paths())?;
|
||||
|
||||
let backend = self.cfg().proxy.backend;
|
||||
let main_program = match backend {
|
||||
|
||||
@@ -236,14 +236,18 @@ pub fn zapret2_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<Uni
|
||||
// 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()))?;
|
||||
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.
|
||||
pub fn options_file(argv: &[String]) -> String {
|
||||
/// 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('"', "\\\""));
|
||||
@@ -253,7 +257,61 @@ pub fn options_file(argv: &[String]) -> String {
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
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
|
||||
@@ -322,7 +380,8 @@ mod tests {
|
||||
#[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), "--filter-tcp=443\n\"--wf-raw-part=inbound and tcp.Payload[0] == 0x16\"\n\"--x=\\\"a\\\"\"\n");
|
||||
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]
|
||||
|
||||
Reference in new issue
Block a user