zapret on or off and its engine; for Flowseal's presets, the preset (the release's own list, matched as the service matches names) and game traffic; for zapret2, learning, IPv6 and the strategy log; the sites to handle besides the engine's lists and the sites to leave alone; TCP timestamps. News from the service replaces what the user has not changed, never what they are typing; a save shows the list as saved. ps-client: set_path for any one option, set_zapret_sites (tidied, deduplicated). gui-shot.sh takes ordered steps: click, type, key, wait. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
322 lines
12 KiB
Rust
322 lines
12 KiB
Rust
//! The configuration edits proxy-ctl and the app make, on the configuration as JSON (what
|
|
//! `config-get` returns). Each can be made again on a newer configuration, which
|
|
//! [`Client::edit`](crate::Client::edit) does when another change came first.
|
|
|
|
use anyhow::{Result, anyhow, bail};
|
|
use serde_json::{Value, json};
|
|
|
|
/// The list at `path`, made (with the objects above it) when missing.
|
|
pub fn arr<'a>(v: &'a mut Value, path: &[&str]) -> &'a mut Vec<Value> {
|
|
let mut cur = v;
|
|
for p in path {
|
|
if cur.get(*p).is_none_or(Value::is_null) {
|
|
cur[*p] = if *p == path[path.len() - 1] { json!([]) } else { json!({}) };
|
|
}
|
|
cur = cur.get_mut(*p).unwrap();
|
|
}
|
|
cur.as_array_mut().expect("a list")
|
|
}
|
|
|
|
/// A tag for a link without one: its remark, else its host.
|
|
pub fn link_tag(link: &str) -> String {
|
|
if let Some((_, remark)) = link.split_once('#') {
|
|
let t = ps_core::links::subscription::slugify_tag(&ps_core::links::py::unquote(remark));
|
|
if t != "proxy" {
|
|
return t;
|
|
}
|
|
}
|
|
let host = link.split("://").nth(1).unwrap_or("").split(['@']).last().unwrap_or("").split([':', '/', '?', '#']).next().unwrap_or("");
|
|
let t = ps_core::links::subscription::slugify_tag(host);
|
|
if t.is_empty() { "outbound".into() } else { t }
|
|
}
|
|
|
|
/// A tag for a subscription without one: its host.
|
|
pub fn subscription_tag(url: &str) -> String {
|
|
let host = ps_core::links::subscription::url_parts::split(url).ok().and_then(|u| u.hostname).unwrap_or_else(|| "sub".into());
|
|
ps_core::links::subscription::slugify_tag(&host)
|
|
}
|
|
|
|
/// What an outbound is made from: a share link, or a backend's own JSON for one.
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub enum OutboundSource {
|
|
Link(String),
|
|
SingBoxJson(Value),
|
|
XrayJson(Value),
|
|
}
|
|
|
|
impl OutboundSource {
|
|
/// A link, or JSON (XRay's has a `protocol`, sing-box's a `type`). A link is checked
|
|
/// here: the service would only say it left the outbound out.
|
|
pub fn parse(text: &str) -> Result<Self> {
|
|
let text = text.trim();
|
|
if text.starts_with('{') {
|
|
let json: Value = serde_json::from_str(text).map_err(|e| anyhow!("not JSON: {e}"))?;
|
|
return Ok(if json.get("protocol").is_some() { Self::XrayJson(json) } else { Self::SingBoxJson(json) });
|
|
}
|
|
ps_core::links::build_outbound(text, "check", ps_core::links::LinkBackend::SingBox)
|
|
.or_else(|_| ps_core::links::build_outbound(text, "check", ps_core::links::LinkBackend::Xray))
|
|
.map_err(|e| anyhow!("{e}"))?;
|
|
Ok(Self::Link(text.to_owned()))
|
|
}
|
|
}
|
|
|
|
pub fn add_outbound(c: &mut Value, tag: &str, source: &OutboundSource, detour: Option<&str>) -> Result<()> {
|
|
let list = arr(c, &["proxy", "outbounds"]);
|
|
if list.iter().any(|o| o["tag"] == tag) {
|
|
bail!("an outbound '{tag}' exists");
|
|
}
|
|
let mut ob = match source {
|
|
OutboundSource::Link(link) => json!({ "tag": tag, "url": link }),
|
|
OutboundSource::SingBoxJson(j) => json!({ "tag": tag, "singBoxJson": j }),
|
|
OutboundSource::XrayJson(j) => json!({ "tag": tag, "xrayJson": j }),
|
|
};
|
|
if let Some(d) = detour {
|
|
ob["detour"] = d.into();
|
|
}
|
|
list.push(ob);
|
|
Ok(())
|
|
}
|
|
|
|
pub fn remove_outbound(c: &mut Value, tag: &str) -> Result<()> {
|
|
let list = arr(c, &["proxy", "outbounds"]);
|
|
let before = list.len();
|
|
list.retain(|o| o["tag"] != tag);
|
|
if list.len() == before {
|
|
bail!("no outbound '{tag}' in the configuration");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn add_subscription(c: &mut Value, tag: &str, url: &str) -> Result<()> {
|
|
let list = arr(c, &["proxy", "subscriptions"]);
|
|
if list.iter().any(|s| s["tag"] == tag) {
|
|
bail!("a subscription '{tag}' exists");
|
|
}
|
|
list.push(json!({ "tag": tag, "url": url }));
|
|
Ok(())
|
|
}
|
|
|
|
pub fn remove_subscription(c: &mut Value, tag: &str) -> Result<()> {
|
|
let list = arr(c, &["proxy", "subscriptions"]);
|
|
let before = list.len();
|
|
list.retain(|s| s["tag"] != tag);
|
|
if list.len() == before {
|
|
bail!("no subscription '{tag}'");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// A rule's matches, sorted into their kinds: domains, addresses, `geosite:`, `geoip:`,
|
|
/// `ruleset:` and `process:` ones.
|
|
pub fn sort_matches(matches: &[String]) -> Value {
|
|
let mut m = json!({ "domains": [], "ips": [], "geosites": [], "geoips": [], "ruleSets": [], "processNames": [] });
|
|
for x in matches {
|
|
let (key, value) = if let Some(v) = x.strip_prefix("geosite:") {
|
|
("geosites", v.to_owned())
|
|
} else if let Some(v) = x.strip_prefix("geoip:") {
|
|
("geoips", v.to_owned())
|
|
} else if let Some(v) = x.strip_prefix("ruleset:") {
|
|
("ruleSets", v.to_owned())
|
|
} else if let Some(v) = x.strip_prefix("process:") {
|
|
("processNames", v.to_owned())
|
|
} else if x.parse::<std::net::IpAddr>().is_ok() || x.split_once('/').is_some_and(|(a, _)| a.parse::<std::net::IpAddr>().is_ok()) {
|
|
("ips", x.clone())
|
|
} else {
|
|
("domains", x.trim_start_matches('.').to_lowercase())
|
|
};
|
|
m[key].as_array_mut().unwrap().push(value.into());
|
|
}
|
|
m
|
|
}
|
|
|
|
/// Sends `matches` to `target`: into the rule called `name` (the target's name without
|
|
/// one), extended if it exists, made with priority 50 if not.
|
|
pub fn add_rule(c: &mut Value, target: &str, matches: &[String], name: Option<&str>, priority: Option<i64>) -> Result<()> {
|
|
if matches.is_empty() {
|
|
bail!("a rule needs something to match");
|
|
}
|
|
let m = sort_matches(matches);
|
|
let name = name.unwrap_or(target);
|
|
let list = arr(c, &["proxy", "routing", "rules"]);
|
|
if let Some(rule) = list.iter_mut().find(|r| r["name"] == name) {
|
|
for (k, v) in m.as_object().unwrap() {
|
|
let mut merged = rule[k.as_str()].as_array().cloned().unwrap_or_default();
|
|
for x in v.as_array().unwrap() {
|
|
if !merged.contains(x) {
|
|
merged.push(x.clone());
|
|
}
|
|
}
|
|
rule[k.as_str()] = Value::Array(merged);
|
|
}
|
|
rule["outbound"] = target.into();
|
|
if let Some(p) = priority {
|
|
rule["priority"] = p.into();
|
|
}
|
|
} else {
|
|
let mut rule = m;
|
|
rule["name"] = name.into();
|
|
rule["outbound"] = target.into();
|
|
rule["priority"] = priority.unwrap_or(50).into();
|
|
list.push(rule);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn remove_rule(c: &mut Value, name: &str) -> Result<()> {
|
|
let list = arr(c, &["proxy", "routing", "rules"]);
|
|
let before = list.len();
|
|
list.retain(|r| r["name"] != name);
|
|
if list.len() == before {
|
|
bail!("no rule named '{name}'");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn set_rule_disabled(c: &mut Value, name: &str, disabled: bool) -> Result<()> {
|
|
if name.is_empty() {
|
|
bail!("a rule name");
|
|
}
|
|
let list = arr(c, &["proxy", "routing", "rules"]);
|
|
let rule = list.iter_mut().find(|r| r["name"] == name).ok_or_else(|| anyhow!("no rule named '{name}'"))?;
|
|
rule["disabled"] = disabled.into();
|
|
Ok(())
|
|
}
|
|
|
|
pub fn set_proxy_enabled(c: &mut Value, on: bool) {
|
|
c["proxy"]["enable"] = on.into();
|
|
}
|
|
|
|
pub fn set_tun_enabled(c: &mut Value, on: bool) {
|
|
c["proxy"]["tun"]["enable"] = on.into();
|
|
}
|
|
|
|
pub fn set_zapret_enabled(c: &mut Value, on: bool) {
|
|
c["zapret"]["enable"] = on.into();
|
|
}
|
|
|
|
/// The DPI bypass's engine, by upstream's names: `zapret-discord-youtube` (Flowseal's
|
|
/// presets) or `zapret2`.
|
|
pub fn set_zapret_engine(c: &mut Value, engine: &str) -> Result<()> {
|
|
if !matches!(engine, "zapret-discord-youtube" | "zapret2") {
|
|
bail!("the engine is zapret-discord-youtube or zapret2");
|
|
}
|
|
c["zapret"]["engine"] = engine.into();
|
|
Ok(())
|
|
}
|
|
|
|
/// The zapret-discord-youtube preset, e.g. "general (ALT9)".
|
|
pub fn set_zapret_preset(c: &mut Value, name: &str) {
|
|
c["zapret"]["zapret-discord-youtube"]["configName"] = name.into();
|
|
}
|
|
|
|
/// Which game traffic zapret handles: all, tcp, udp or null.
|
|
pub fn set_game_filter(c: &mut Value, filter: &str) -> Result<()> {
|
|
if !matches!(filter, "all" | "tcp" | "udp" | "null") {
|
|
bail!("the game filter is all, tcp, udp or null");
|
|
}
|
|
c["zapret"]["zapret-discord-youtube"]["gameFilter"] = filter.into();
|
|
Ok(())
|
|
}
|
|
|
|
pub fn set_tg_ws_proxy_enabled(c: &mut Value, on: bool) {
|
|
c["tgWsProxy"]["enable"] = on.into();
|
|
}
|
|
|
|
/// Any option by its path, e.g. `["zapret", "zapret2", "ipv6"]`; the objects above it are
|
|
/// made when missing.
|
|
pub fn set_path(c: &mut Value, path: &[&str], value: Value) {
|
|
let mut cur = c;
|
|
for p in path {
|
|
if !cur.is_object() {
|
|
*cur = json!({});
|
|
}
|
|
cur = &mut cur[*p];
|
|
}
|
|
*cur = value;
|
|
}
|
|
|
|
/// The sites an engine also handles and those it leaves alone: for `zapret-discord-youtube`
|
|
/// beside its release's lists, for `zapret2` beside its strategies' own.
|
|
pub fn set_zapret_sites(c: &mut Value, engine: &str, domains: &[String], exclude: &[String]) -> Result<()> {
|
|
if !matches!(engine, "zapret-discord-youtube" | "zapret2") {
|
|
bail!("the engine is zapret-discord-youtube or zapret2");
|
|
}
|
|
let clean = |list: &[String]| -> Vec<Value> {
|
|
let mut out: Vec<Value> = Vec::new();
|
|
for d in list.iter().map(|d| d.trim().trim_start_matches('.').to_lowercase()).filter(|d| !d.is_empty()) {
|
|
if !out.contains(&Value::from(d.as_str())) {
|
|
out.push(d.into());
|
|
}
|
|
}
|
|
out
|
|
};
|
|
c["zapret"][engine]["domains"] = Value::Array(clean(domains));
|
|
c["zapret"][engine]["excludeDomains"] = Value::Array(clean(exclude));
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn outbounds_are_added_once_and_removed() {
|
|
let mut c = json!({});
|
|
let src = OutboundSource::parse("ss://YWVzLTEyOC1nY206cGFzcw@1.2.3.4:8388#My%20Server").unwrap();
|
|
add_outbound(&mut c, "nl", &src, Some("hop")).unwrap();
|
|
assert_eq!(c["proxy"]["outbounds"][0]["detour"], "hop");
|
|
assert!(add_outbound(&mut c, "nl", &src, None).is_err());
|
|
remove_outbound(&mut c, "nl").unwrap();
|
|
assert!(remove_outbound(&mut c, "nl").is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn sources_are_links_or_either_json() {
|
|
assert!(matches!(OutboundSource::parse(r#"{"protocol":"vless"}"#).unwrap(), OutboundSource::XrayJson(_)));
|
|
assert!(matches!(OutboundSource::parse(r#" {"type":"vless"}"#).unwrap(), OutboundSource::SingBoxJson(_)));
|
|
assert!(OutboundSource::parse("not a link").is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn tags_come_from_the_remark_or_the_host() {
|
|
assert_eq!(link_tag("ss://x@1.2.3.4:8388#My%20Server"), "My-Server");
|
|
assert_eq!(link_tag("vless://id@example.com:443?security=tls"), "example-com");
|
|
}
|
|
|
|
#[test]
|
|
fn rules_are_extended_by_name() {
|
|
let mut c = json!({});
|
|
add_rule(&mut c, "direct", &["Example.com".into(), "10.0.0.0/8".into(), "process:steam.exe".into()], None, None).unwrap();
|
|
add_rule(&mut c, "direct", &["example.com".into(), "geosite:cn".into()], None, Some(10)).unwrap();
|
|
let r = &c["proxy"]["routing"]["rules"][0];
|
|
assert_eq!(r["domains"], json!(["example.com"]));
|
|
assert_eq!(r["ips"], json!(["10.0.0.0/8"]));
|
|
assert_eq!(r["processNames"], json!(["steam.exe"]));
|
|
assert_eq!(r["geosites"], json!(["cn"]));
|
|
assert_eq!(r["priority"], 10);
|
|
set_rule_disabled(&mut c, "direct", true).unwrap();
|
|
assert_eq!(c["proxy"]["routing"]["rules"][0]["disabled"], true);
|
|
}
|
|
|
|
#[test]
|
|
fn paths_and_site_lists() {
|
|
let mut c = json!({ "zapret": null });
|
|
set_path(&mut c, &["zapret", "zapret2", "ipv6"], true.into());
|
|
assert_eq!(c["zapret"]["zapret2"]["ipv6"], true);
|
|
set_zapret_sites(&mut c, "zapret2", &[" .Example.com".into(), "".into(), "example.com".into()], &["bank.example".into()]).unwrap();
|
|
assert_eq!(c["zapret"]["zapret2"]["domains"], json!(["example.com"]));
|
|
assert_eq!(c["zapret"]["zapret2"]["excludeDomains"], json!(["bank.example"]));
|
|
assert!(set_zapret_sites(&mut c, "goodbyedpi", &[], &[]).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn zapret_settings_are_checked() {
|
|
let mut c = json!({});
|
|
assert!(set_game_filter(&mut c, "everything").is_err());
|
|
set_game_filter(&mut c, "udp").unwrap();
|
|
assert!(set_zapret_engine(&mut c, "goodbyedpi").is_err());
|
|
set_zapret_engine(&mut c, "zapret2").unwrap();
|
|
assert_eq!(c["zapret"], json!({ "engine": "zapret2", "zapret-discord-youtube": { "gameFilter": "udp" } }));
|
|
}
|
|
}
|