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:
faumarayandClaude Opus 5.5 committed 2026-10-27 01:13:28 +03:00
1 parent da6aafaf1d
commit 4ae30dac3c
12 files changed
+7453 -275

No files matched your search

+2 -1
View File
@@ -75,9 +75,10 @@ jobs:
working-directory: windows
run: nix develop --command rustup toolchain install
# The default members: everything the zip carries, not the app (GPUI) yet.
- name: Test
working-directory: windows
run: nix develop --command cargo test --workspace --locked
run: nix develop --command cargo test --locked
- name: Package
working-directory: windows
+6898 -35
View File
File diff suppressed because it is too large. Load diff
+4 -1
View File
@@ -1,6 +1,8 @@
[workspace]
resolver = "2"
members = ["crates/ps-core", "crates/ps-ipc", "crates/ps-service", "crates/ps-ctl"]
members = ["crates/ps-core", "crates/ps-ipc", "crates/ps-service", "crates/ps-client", "crates/ps-ctl", "crates/ps-gui"]
# The app (GPUI) builds only when asked for: `-p ps-gui` or `--workspace`.
default-members = ["crates/ps-core", "crates/ps-ipc", "crates/ps-service", "crates/ps-client", "crates/ps-ctl"]
[workspace.package]
version = "0.1.0-pre.2"
@@ -31,6 +33,7 @@ sha2 = "0.10"
zip = { version = "2", default-features = false, features = ["deflate"] }
ps-core = { path = "crates/ps-core" }
ps-ipc = { path = "crates/ps-ipc" }
ps-client = { path = "crates/ps-client" }
[profile.release]
lto = "thin"
+1 -1
View File
@@ -140,7 +140,7 @@ See [`THIRD-PARTY.md`](THIRD-PARTY.md) for their licenses and sources.
On Linux with Nix: `nix develop` here (this directory has its own `flake.nix`), then
```sh
cargo test --workspace # everything, sing-box and xray from the shell
cargo test # everything but the app; sing-box and xray from the shell
python3 -I tools/parity/links.py # link parsing against upstream's Python
tools/package.sh # the release zip, in dist/
nix shell nixpkgs#wineWow64Packages.stable -c tools/winws-dry-run.sh dist/ProxySuite-*/components
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "ps-client"
description = "Proxy Suite for Windows: the service's client side, for proxy-ctl and the app"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
ps-core.workspace = true
ps-ipc.workspace = true
anyhow.workspace = true
serde_json.workspace = true
[dev-dependencies]
tokio.workspace = true
+276
View File
@@ -0,0 +1,276 @@
//! 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: `zapret` (Flowseal's presets) or `zapret2`.
pub fn set_zapret_engine(c: &mut Value, engine: &str) -> Result<()> {
if !matches!(engine, "zapret" | "zapret2") {
bail!("the engine is zapret 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();
}
#[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 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" } }));
}
}
+129
View File
@@ -0,0 +1,129 @@
//! The service's client side, shared by proxy-ctl and the app: requests, configuration
//! edits made against the revision they read, and the edits both make ([`edits`]).
pub mod edits;
use anyhow::{Result, bail};
use ps_ipc::transport::{self, Address};
use ps_ipc::{Request, Response};
use serde_json::Value;
/// What a configuration edit got back: the new revision, the validator's notes, and the
/// error applying it, when it was saved but did not apply.
#[derive(Debug, Clone, Default)]
pub struct Saved {
pub revision: Option<u64>,
pub issues: Vec<Issue>,
pub apply_error: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Issue {
pub severity: String,
pub path: String,
pub message: String,
}
impl std::fmt::Display for Issue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}: {}", self.severity, self.path, self.message)
}
}
/// The validator's notes in a response's data.
pub fn issues(data: &Value) -> Vec<Issue> {
data["issues"]
.as_array()
.into_iter()
.flatten()
.map(|i| Issue {
severity: i["severity"].as_str().unwrap_or("").to_owned(),
path: i["path"].as_str().unwrap_or("").to_owned(),
message: i["message"].as_str().unwrap_or("").to_owned(),
})
.collect()
}
#[derive(Debug, Clone)]
pub struct Client {
pub addr: Address,
}
impl Client {
pub fn new(addr: Address) -> Self {
Self { addr }
}
/// One request; a refusal is an error carrying the service's words and its notes.
pub 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());
for i in issues(&resp.data) {
msg.push_str(&format!("\n {i}"));
}
bail!(msg);
}
Ok(resp.data)
}
/// Reads the configuration, lets `edit` change it, and writes it back against the
/// revision read; a concurrent change is read again and `edit` made again.
pub async fn edit(&self, edit: impl Fn(&mut Value) -> Result<()>) -> Result<Saved> {
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?;
return Ok(Saved {
revision: r["revision"].as_u64(),
issues: issues(&r),
apply_error: r["error"].as_str().map(str::to_owned),
});
}
}
}
bail!("the configuration kept changing; try again")
}
/// Log lines (every unit's without `unit`) as `(unit, line)`, the last `lines` and, with
/// `follow`, each new one, until `each` says stop.
pub async fn logs(&self, unit: Option<String>, lines: usize, follow: bool, mut each: impl FnMut(&str, &str) -> bool) -> Result<()> {
let mut take = |r: Response| {
let one = |l: &Value| (l["unit"].as_str().unwrap_or("").to_owned(), l["line"].as_str().unwrap_or("").to_owned());
match &r.data {
Value::Array(ls) => ls.iter().map(one).all(|(u, l)| each(&u, &l)),
d if d.is_object() => {
let (u, l) = one(d);
each(&u, &l)
}
_ => true,
}
};
let req = Request::Logs { unit, lines, follow };
if follow {
let mut refused = None;
transport::stream(&self.addr, &req, |r| {
if !r.ok {
refused = Some(r.error.unwrap_or_else(|| "failed".into()));
return false;
}
take(r)
})
.await?;
if let Some(e) = refused {
bail!(e);
}
} else {
let r = transport::call(&self.addr, &req).await?;
if !r.ok {
bail!(r.error.unwrap_or_else(|| "failed".into()));
}
take(r);
}
Ok(())
}
}
+1
View File
@@ -12,6 +12,7 @@ path = "src/main.rs"
[dependencies]
ps-core.workspace = true
ps-ipc.workspace = true
ps-client.workspace = true
anyhow.workspace = true
serde_json.workspace = true
tokio.workspace = true
+47 -237
View File
@@ -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?,
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "ps-gui"
description = "Proxy Suite for Windows: the desktop app"
version.workspace = true
edition.workspace = true
license.workspace = true
[[bin]]
name = "proxy-suite"
path = "src/main.rs"
[dependencies]
gpui-kit = { version = "0.8.1", features = ["tree-sitter"] }
+29
View File
@@ -0,0 +1,29 @@
//! proxy-suite: the desktop app. A client of the service, as proxy-ctl is.
#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")]
use gpui_kit::component::button::*;
use gpui_kit::component::*;
use gpui_kit::*;
struct Hello;
impl Render for Hello {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.v_flex()
.gap_2()
.size_full()
.items_center()
.justify_center()
.child("Proxy Suite")
.child(Button::new("ok").primary().label("On"))
}
}
fn main() {
gpui_kit::application().with_assets(gpui_kit::assets::Assets).run(|cx| {
gpui_kit::init(cx);
gpui_kit::open_window(WindowOptions::default(), cx, |_, cx| cx.new(|_| Hello)).expect("opening the window");
});
}
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# The app without a display: run on Xvfb with Mesa's software Vulkan (lavapipe), and a
# screenshot of it once it has drawn. For checking the GUI on Linux, in the dev shell.
#
# tools/gui-shot.sh OUT.png [SECONDS] [-- APP ARGS...] (APP=target/debug/proxy-suite)
#
# With SHOT_KEYS="key ..." the keys (xdotool names) are typed into the window before the shot.
set -euo pipefail
OUT=$(realpath -m "${1:?the screenshot, a .png}"); shift
WAIT=6
if [ $# -gt 0 ] && [ "$1" != "--" ]; then WAIT=$1; shift; fi
[ "${1:-}" = "--" ] && shift
cd "$(dirname "$0")/.."
APP=$(realpath "${APP:-target/debug/proxy-suite}")
GEOMETRY=${GEOMETRY:-1280x820}
path() { nix build --no-link --print-out-paths --inputs-from . "nixpkgs#$1.out" | head -1; }
XVFB=$(path xvfb) MESA=$(path mesa) MAGICK=$(path imagemagick) XDOTOOL=$(path xdotool)
n=90
while [ -e "/tmp/.X11-unix/X$n" ] || [ -e "/tmp/.X$n-lock" ]; do n=$((n + 1)); done
"$XVFB/bin/Xvfb" ":$n" -screen 0 "${GEOMETRY}x24" -nolisten tcp >/dev/null 2>&1 &
XPID=$!
trap 'kill "${APID:-}" "$XPID" 2>/dev/null || true' EXIT
for _ in $(seq 50); do [ -e "/tmp/.X11-unix/X$n" ] && break; sleep 0.1; done
env -u WAYLAND_DISPLAY DISPLAY=":$n" VK_ICD_FILENAMES="$MESA/share/vulkan/icd.d/lvp_icd.x86_64.json" \
"$APP" "$@" >"${OUT%.png}.log" 2>&1 &
APID=$!
sleep "$WAIT"
kill -0 "$APID" 2>/dev/null || { echo "the app exited:"; tail -20 "${OUT%.png}.log"; exit 1; }
if [ -n "${SHOT_KEYS:-}" ]; then
# shellcheck disable=SC2086
DISPLAY=":$n" "$XDOTOOL/bin/xdotool" key --delay 150 $SHOT_KEYS
sleep 1.5
fi
DISPLAY=":$n" "$MAGICK/bin/magick" import -window root "$OUT"
echo "$OUT"