windows: ps-client shared by proxy-ctl and the app; the app's first window
- ps-client: the service's client side, moved out of proxy-ctl: calls, configuration edits against the revision read (retried on a concurrent change), log following, and the edits themselves as functions on the configuration (outbounds, subscriptions, rules, zapret, tg-ws-proxy), now unit-tested. proxy-ctl does what it did, through it; a refused log follow is now an error instead of nothing. - ps-gui: proxy-suite, the desktop app on GPUI (gpui-kit 0.8.1); only a first window yet. Not in default-members: plain cargo build/test and the release workflow's tests leave GPUI out. - tools/gui-shot.sh: runs the app on Xvfb with Mesa's software Vulkan and screenshots it, to check the GUI on Linux without a display. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
da6aafaf1d
commit
4ae30dac3c
12 files changed
+7453
-275
No files matched your search
@@ -2,11 +2,13 @@
|
||||
|
||||
use std::io::Read;
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::{Args, Parser, Subcommand};
|
||||
use ps_ipc::transport::{self, Address};
|
||||
use ps_ipc::{Request, Response};
|
||||
use serde_json::{Value, json};
|
||||
use ps_client::edits::{self, OutboundSource};
|
||||
use ps_client::{Client, Saved};
|
||||
use ps_ipc::Request;
|
||||
use ps_ipc::transport::Address;
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "proxy-ctl", version, about = "Control Proxy Suite", disable_help_subcommand = true)]
|
||||
@@ -194,51 +196,29 @@ enum RulesetsVerb {
|
||||
}
|
||||
|
||||
struct Ctl {
|
||||
addr: Address,
|
||||
client: Client,
|
||||
json: bool,
|
||||
}
|
||||
|
||||
impl Ctl {
|
||||
async fn call(&self, req: Request) -> Result<Value> {
|
||||
let resp: Response = transport::call(&self.addr, &req).await?;
|
||||
if !resp.ok {
|
||||
let mut msg = resp.error.unwrap_or_else(|| "failed".into());
|
||||
if let Some(issues) = resp.data.get("issues").and_then(Value::as_array) {
|
||||
for i in issues {
|
||||
msg.push_str(&format!("\n {} {}: {}", i["severity"].as_str().unwrap_or(""), i["path"].as_str().unwrap_or(""), i["message"].as_str().unwrap_or("")));
|
||||
}
|
||||
}
|
||||
bail!(msg);
|
||||
}
|
||||
Ok(resp.data)
|
||||
self.client.call(req).await
|
||||
}
|
||||
|
||||
fn print(&self, v: &Value) {
|
||||
println!("{}", serde_json::to_string_pretty(v).unwrap());
|
||||
}
|
||||
|
||||
/// Reads the configuration, lets `edit` change it, writes it back against the revision
|
||||
/// read; a concurrent change is retried.
|
||||
async fn edit(&self, edit: impl Fn(&mut Value) -> Result<()>) -> Result<Value> {
|
||||
for _ in 0..3 {
|
||||
let got = self.call(Request::ConfigGet).await?;
|
||||
let mut config = got["config"].clone();
|
||||
edit(&mut config)?;
|
||||
match self.call(Request::ConfigSet { config, base: got["revision"].as_u64() }).await {
|
||||
Err(e) if e.to_string().contains("changed since revision") => continue,
|
||||
other => {
|
||||
let r = other?;
|
||||
for i in r["issues"].as_array().into_iter().flatten() {
|
||||
eprintln!("{}: {}: {}", i["severity"].as_str().unwrap_or(""), i["path"].as_str().unwrap_or(""), i["message"].as_str().unwrap_or(""));
|
||||
}
|
||||
if let Some(e) = r["error"].as_str() {
|
||||
eprintln!("saved, but not applied: {e}");
|
||||
}
|
||||
return Ok(r);
|
||||
}
|
||||
}
|
||||
/// A configuration edit ([`Client::edit`]), and what the validator said of it.
|
||||
async fn edit(&self, edit: impl Fn(&mut Value) -> Result<()>) -> Result<Saved> {
|
||||
let saved = self.client.edit(edit).await?;
|
||||
for i in &saved.issues {
|
||||
eprintln!("{i}");
|
||||
}
|
||||
bail!("the configuration kept changing; try again")
|
||||
if let Some(e) = &saved.apply_error {
|
||||
eprintln!("saved, but not applied: {e}");
|
||||
}
|
||||
Ok(saved)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -257,52 +237,6 @@ fn read_file_arg(file: &str) -> Result<Value> {
|
||||
serde_json::from_str(&text).with_context(|| format!("{file} is not JSON"))
|
||||
}
|
||||
|
||||
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.
|
||||
fn tag_for(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 rule's matches, sorted into their kinds.
|
||||
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
|
||||
}
|
||||
|
||||
async fn status(ctl: &Ctl) -> Result<()> {
|
||||
let s = ctl.call(Request::Status).await?;
|
||||
if ctl.json {
|
||||
@@ -365,64 +299,20 @@ async fn outbounds(ctl: &Ctl, verb: Option<OutboundVerb>) -> Result<()> {
|
||||
}
|
||||
}
|
||||
OutboundVerb::Add { args, detour } => {
|
||||
let (tag, link) = match args.as_slice() {
|
||||
let (tag, text) = match args.as_slice() {
|
||||
[link] => {
|
||||
let link = read_arg(link)?;
|
||||
(tag_for(&link), link)
|
||||
(edits::link_tag(&link), link)
|
||||
}
|
||||
[tag, link] => (tag.clone(), read_arg(link)?),
|
||||
_ => bail!("usage: proxy outbounds add [tag] <link|->"),
|
||||
};
|
||||
if link.trim_start().starts_with('{') {
|
||||
let json: Value = serde_json::from_str(&link).context("not JSON")?;
|
||||
let key = if json.get("protocol").is_some() { "xrayJson" } else { "singBoxJson" };
|
||||
let tag2 = tag.clone();
|
||||
ctl.edit(move |c| {
|
||||
let list = arr(c, &["proxy", "outbounds"]);
|
||||
if list.iter().any(|o| o["tag"] == tag2.as_str()) {
|
||||
bail!("an outbound '{tag2}' exists");
|
||||
}
|
||||
let mut ob = json!({ "tag": tag2, key: json });
|
||||
if let Some(d) = &detour {
|
||||
ob["detour"] = d.clone().into();
|
||||
}
|
||||
list.push(ob);
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
} else {
|
||||
// Checked here first: the service would only say the outbound was left out.
|
||||
ps_core::links::build_outbound(&link, &tag, ps_core::links::LinkBackend::SingBox)
|
||||
.or_else(|_| ps_core::links::build_outbound(&link, &tag, ps_core::links::LinkBackend::Xray))
|
||||
.map_err(|e| anyhow!("{e}"))?;
|
||||
let tag2 = tag.clone();
|
||||
ctl.edit(move |c| {
|
||||
let list = arr(c, &["proxy", "outbounds"]);
|
||||
if list.iter().any(|o| o["tag"] == tag2.as_str()) {
|
||||
bail!("an outbound '{tag2}' exists");
|
||||
}
|
||||
let mut ob = json!({ "tag": tag2, "url": link });
|
||||
if let Some(d) = &detour {
|
||||
ob["detour"] = d.clone().into();
|
||||
}
|
||||
list.push(ob);
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
let source = OutboundSource::parse(&text)?;
|
||||
ctl.edit(|c| edits::add_outbound(c, &tag, &source, detour.as_deref())).await?;
|
||||
println!("added {tag}");
|
||||
}
|
||||
OutboundVerb::Rm { tag } => {
|
||||
ctl.edit(|c| {
|
||||
let list = arr(c, &["proxy", "outbounds"]);
|
||||
let before = list.len();
|
||||
list.retain(|o| o["tag"] != tag.as_str());
|
||||
if list.len() == before {
|
||||
bail!("no outbound '{tag}' in the configuration");
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
ctl.edit(|c| edits::remove_outbound(c, &tag)).await?;
|
||||
println!("removed {tag}");
|
||||
}
|
||||
OutboundVerb::Disable { tag } => {
|
||||
@@ -476,35 +366,16 @@ async fn subs(ctl: &Ctl, verb: Option<SubsVerb>) -> Result<()> {
|
||||
let (tag, url) = match args.as_slice() {
|
||||
[url] => {
|
||||
let url = read_arg(url)?;
|
||||
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), url)
|
||||
(edits::subscription_tag(&url), url)
|
||||
}
|
||||
[tag, url] => (tag.clone(), read_arg(url)?),
|
||||
_ => bail!("usage: proxy subs add [tag] <url|->"),
|
||||
};
|
||||
let tag2 = tag.clone();
|
||||
ctl.edit(move |c| {
|
||||
let list = arr(c, &["proxy", "subscriptions"]);
|
||||
if list.iter().any(|s| s["tag"] == tag2.as_str()) {
|
||||
bail!("a subscription '{tag2}' exists");
|
||||
}
|
||||
list.push(json!({ "tag": tag2, "url": url }));
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
ctl.edit(|c| edits::add_subscription(c, &tag, &url)).await?;
|
||||
println!("added {tag}; fetching it");
|
||||
}
|
||||
SubsVerb::Rm { tag } => {
|
||||
ctl.edit(|c| {
|
||||
let list = arr(c, &["proxy", "subscriptions"]);
|
||||
let before = list.len();
|
||||
list.retain(|s| s["tag"] != tag.as_str());
|
||||
if list.len() == before {
|
||||
bail!("no subscription '{tag}'");
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
ctl.edit(|c| edits::remove_subscription(c, &tag)).await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -536,73 +407,27 @@ async fn rules(ctl: &Ctl, verb: Option<RulesVerb>) -> Result<()> {
|
||||
if matches.is_empty() {
|
||||
bail!("usage: proxy rules add <target> <match...>");
|
||||
}
|
||||
let m = sort_matches(&matches);
|
||||
let name = name.unwrap_or_else(|| target.clone());
|
||||
ctl.edit(|c| {
|
||||
let list = arr(c, &["proxy", "routing", "rules"]);
|
||||
// No --name: the rule named after the target, extended.
|
||||
if let Some(rule) = list.iter_mut().find(|r| r["name"] == name.as_str()) {
|
||||
for (k, v) in m.as_object().unwrap() {
|
||||
let have = rule[k.as_str()].as_array().cloned().unwrap_or_default();
|
||||
let mut merged = have;
|
||||
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.clone().into();
|
||||
if let Some(p) = priority {
|
||||
rule["priority"] = p.into();
|
||||
}
|
||||
} else {
|
||||
let mut rule = m.clone();
|
||||
rule["name"] = name.clone().into();
|
||||
rule["outbound"] = target.clone().into();
|
||||
rule["priority"] = priority.unwrap_or(50).into();
|
||||
list.push(rule);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
ctl.edit(|c| edits::add_rule(c, &target, &matches, name.as_deref(), priority)).await?;
|
||||
}
|
||||
RulesVerb::Rm { name } => {
|
||||
ctl.edit(|c| {
|
||||
let list = arr(c, &["proxy", "routing", "rules"]);
|
||||
let before = list.len();
|
||||
list.retain(|r| r["name"] != name.as_str());
|
||||
if list.len() == before {
|
||||
bail!("no rule named '{name}'");
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
ctl.edit(|c| edits::remove_rule(c, &name)).await?;
|
||||
}
|
||||
RulesVerb::Disable { name } => {
|
||||
ctl.edit(|c| edits::set_rule_disabled(c, &name, true)).await?;
|
||||
}
|
||||
RulesVerb::Enable { name } => {
|
||||
ctl.edit(|c| edits::set_rule_disabled(c, &name, false)).await?;
|
||||
}
|
||||
RulesVerb::Disable { name } | RulesVerb::Enable { name } if name.is_empty() => bail!("a rule name"),
|
||||
RulesVerb::Disable { name } => set_rule_disabled(ctl, &name, true).await?,
|
||||
RulesVerb::Enable { name } => set_rule_disabled(ctl, &name, false).await?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_rule_disabled(ctl: &Ctl, name: &str, disabled: bool) -> Result<()> {
|
||||
ctl.edit(|c| {
|
||||
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(())
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn proxy(ctl: &Ctl, verb: Option<ProxyVerb>) -> Result<()> {
|
||||
match verb.unwrap_or(ProxyVerb::Status) {
|
||||
ProxyVerb::Status => status(ctl).await?,
|
||||
ProxyVerb::On => {
|
||||
ctl.edit(|c| {
|
||||
c["proxy"]["enable"] = true.into();
|
||||
edits::set_proxy_enabled(c, true);
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
@@ -648,7 +473,7 @@ async fn proxy(ctl: &Ctl, verb: Option<ProxyVerb>) -> Result<()> {
|
||||
}
|
||||
OnOff::On => {
|
||||
ctl.edit(|c| {
|
||||
c["proxy"]["tun"]["enable"] = true.into();
|
||||
edits::set_tun_enabled(c, true);
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
@@ -679,27 +504,22 @@ async fn zapret(ctl: &Ctl, verb: Option<ZapretVerb>) -> Result<()> {
|
||||
v @ (ZapretVerb::On | ZapretVerb::Off) => {
|
||||
let on = matches!(v, ZapretVerb::On);
|
||||
ctl.edit(|c| {
|
||||
c["zapret"]["enable"] = on.into();
|
||||
edits::set_zapret_enabled(c, on);
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
ZapretVerb::Preset { name } => {
|
||||
ctl.edit(|c| {
|
||||
c["zapret"]["zapret-discord-youtube"]["configName"] = name.clone().into();
|
||||
edits::set_zapret_preset(c, &name);
|
||||
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?;
|
||||
// Checked before asking the service for anything.
|
||||
edits::set_game_filter(&mut Value::Null, &filter)?;
|
||||
ctl.edit(|c| edits::set_game_filter(c, &filter)).await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -740,29 +560,19 @@ async fn real_main() -> Result<()> {
|
||||
Some(s) => Address::Unix(s.into()),
|
||||
None => Address::default_for_platform(),
|
||||
};
|
||||
let ctl = Ctl { addr, json: cli.json };
|
||||
let ctl = Ctl { client: Client::new(addr), json: cli.json };
|
||||
match cli.command {
|
||||
Cmd::Status => status(&ctl).await?,
|
||||
Cmd::Restart { units } => {
|
||||
ctl.call(Request::Restart { units }).await?;
|
||||
}
|
||||
Cmd::Logs { units, lines, follow } => {
|
||||
let unit = units.first().cloned();
|
||||
let print = |r: Response| {
|
||||
if let Some(arr) = r.data.as_array() {
|
||||
for l in arr {
|
||||
println!("{}: {}", l["unit"].as_str().unwrap_or(""), l["line"].as_str().unwrap_or(""));
|
||||
}
|
||||
} else if r.data.is_object() {
|
||||
println!("{}: {}", r.data["unit"].as_str().unwrap_or(""), r.data["line"].as_str().unwrap_or(""));
|
||||
}
|
||||
true
|
||||
};
|
||||
if follow {
|
||||
transport::stream(&ctl.addr, &Request::Logs { unit, lines, follow: true }, print).await?;
|
||||
} else {
|
||||
print(transport::call(&ctl.addr, &Request::Logs { unit, lines, follow: false }).await?);
|
||||
}
|
||||
ctl.client
|
||||
.logs(units.first().cloned(), lines, follow, |unit, line| {
|
||||
println!("{unit}: {line}");
|
||||
true
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
Cmd::Proxy(p) => proxy(&ctl, p.verb).await?,
|
||||
Cmd::Zapret { verb } => zapret(&ctl, verb).await?,
|
||||
|
||||
Reference in new issue
Block a user