windows: the service, its API and proxy-ctl

ps-ipc: line-delimited JSON over a named pipe whose ACL admits SYSTEM,
Administrators and (with userControl) the interactive user; the caller
is identified by impersonation, never by what it claims. A Unix socket
stands in off Windows.

ps-service (proxy-suite-service.exe): a Windows service, or --console.
Keeps the configuration with revisions, runtime state and generated
secrets; renders, checks with sing-box check before replacing what
runs, and supervises the backends (restart with backoff, start limit,
logs in a ring and a file, a Job Object on Windows). Enforces scopes,
admin-only edits and secret redaction that round-trips. Fetches
subscriptions and rule sets through the proxy or directly with
upstream's redirect rules, on timers.

ps-ctl (proxy-ctl.exe): status, restart, logs [-f], config get/set/
validate, and proxy on/off, outbounds, pin, mode, subs, rules,
rulesets, tun and config.

An end-to-end test runs it all offline: a sing-box Shadowsocks server,
the service, proxy-ctl adding the outbound, a page fetched through the
local proxy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-26 23:13:19 +03:00
1 parent 918cdc9a75
commit 41c8ed4406
25 files changed
+5411 -7

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
[package]
name = "ps-ctl"
description = "Proxy Suite for Windows: proxy-ctl, the command line"
version.workspace = true
edition.workspace = true
license.workspace = true
[[bin]]
name = "proxy-ctl"
path = "src/main.rs"
[dependencies]
ps-core.workspace = true
ps-ipc.workspace = true
anyhow.workspace = true
serde_json.workspace = true
tokio.workspace = true
clap.workspace = true
[dev-dependencies]
serde_json.workspace = true
+696
View File
@@ -0,0 +1,696 @@
//! proxy-ctl: upstream's command line, over the service's API.
use std::io::Read;
use anyhow::{Context, Result, anyhow, bail};
use clap::{Args, Parser, Subcommand};
use ps_ipc::transport::{self, Address};
use ps_ipc::{Request, Response};
use serde_json::{Value, json};
#[derive(Parser)]
#[command(name = "proxy-ctl", version, about = "Control Proxy Suite", disable_help_subcommand = true)]
struct Cli {
/// The service's pipe or socket.
#[arg(long, global = true, value_name = "ADDRESS")]
socket: Option<String>,
/// Print what the service answers, as JSON.
#[arg(long, global = true)]
json: bool,
#[command(subcommand)]
command: Cmd,
}
#[derive(Subcommand)]
enum Cmd {
/// Services and routing mode.
Status,
/// Restart running services.
Restart { units: Vec<String> },
/// Show logs (all units, or the ones named); -f follows.
Logs {
units: Vec<String>,
#[arg(short = 'n', long, default_value_t = 100)]
lines: usize,
#[arg(short = 'f', long)]
follow: bool,
},
/// The local proxy.
Proxy(ProxyArgs),
/// The whole configuration.
Config {
#[command(subcommand)]
verb: ConfigVerb,
},
}
#[derive(Subcommand)]
enum ConfigVerb {
/// Print it (secrets hidden without the secrets scope).
Get,
/// Replace it with a file's (or stdin's, with -).
Set { file: String },
/// Check a file without taking it.
Validate { file: String },
}
#[derive(Args)]
struct ProxyArgs {
#[command(subcommand)]
verb: Option<ProxyVerb>,
}
#[derive(Subcommand)]
enum ProxyVerb {
Status,
On,
Off,
/// Outbounds, their source, and the current pick.
Outbounds {
#[command(subcommand)]
verb: Option<OutboundVerb>,
},
/// Always use this outbound.
Pin {
tag: String,
#[arg(long = "in", value_name = "GROUP")]
group: Option<String>,
},
/// Back to automatic selection.
Unpin {
#[arg(long = "in", value_name = "GROUP")]
group: Option<String>,
},
/// Show or override the routing mode: default, whitelist, blacklist, all-proxy, all-bypass.
Mode { mode: Option<String> },
/// Subscriptions.
Subs {
#[command(subcommand)]
verb: Option<SubsVerb>,
},
/// Routing rules.
Rules {
#[command(subcommand)]
verb: Option<RulesVerb>,
},
/// Rule sets: update refetches them.
Rulesets {
#[command(subcommand)]
verb: Option<RulesetsVerb>,
},
/// Global TUN mode.
Tun {
#[command(subcommand)]
verb: Option<OnOff>,
},
/// The config the backend runs.
Config,
}
#[derive(Subcommand)]
enum OnOff {
Status,
On,
Off,
}
#[derive(Subcommand)]
enum OutboundVerb {
List,
/// Add an outbound from a link (- reads it from stdin).
Add {
/// The tag, then the link; or the link alone.
args: Vec<String>,
#[arg(long)]
detour: Option<String>,
},
Rm { tag: String },
Disable { tag: String },
Enable { tag: String },
/// Delay through each (all, or the named).
Test { tags: Vec<String> },
/// Its link.
Link { tag: String },
}
#[derive(Subcommand)]
enum SubsVerb {
List,
Update { tag: Option<String> },
/// Add a subscription (no tag: named after its host; - reads the URL from stdin).
Add { args: Vec<String> },
Rm { tag: String },
}
#[derive(Subcommand)]
enum RulesVerb {
List,
/// Send domains, addresses, geosite:x, geoip:x, ruleset:x or process:x.exe to a target.
Add {
target: String,
matches: Vec<String>,
#[arg(long)]
name: Option<String>,
#[arg(long)]
priority: Option<i64>,
},
Rm { name: String },
Disable { name: String },
Enable { name: String },
}
#[derive(Subcommand)]
enum RulesetsVerb {
List,
Update,
}
struct Ctl {
addr: Address,
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)
}
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);
}
}
}
bail!("the configuration kept changing; try again")
}
}
fn read_arg(value: &str) -> Result<String> {
if value == "-" {
let mut s = String::new();
std::io::stdin().read_to_string(&mut s)?;
Ok(s.trim().to_owned())
} else {
Ok(value.to_owned())
}
}
fn read_file_arg(file: &str) -> Result<Value> {
let text = if file == "-" { read_arg("-")? } else { std::fs::read_to_string(file).with_context(|| format!("reading {file}"))? };
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 {
ctl.print(&s);
return Ok(());
}
let p = &s["proxy"];
println!(
"proxy: {} ({}, {}){}",
p["state"].as_str().unwrap_or("?"),
p["backend"].as_str().unwrap_or("?"),
p["listener"].as_str().unwrap_or("?"),
if p["tun"] == true { ", global TUN" } else { "" }
);
println!(
" selection {}, mode {}{}",
p["selection"].as_str().unwrap_or("?"),
p["mode"].as_str().unwrap_or("default"),
p["pinned"].as_str().map(|t| format!(", pinned to {t}")).unwrap_or_default()
);
for u in s["units"].as_array().into_iter().flatten() {
println!("{:32} {}", u["name"].as_str().unwrap_or(""), u["state"].as_str().unwrap_or(""));
}
if let Some(e) = s["error"].as_str() {
println!("error: {e}");
}
for w in s["warnings"].as_array().into_iter().flatten() {
println!("warning: {}", w.as_str().unwrap_or(""));
}
Ok(())
}
async fn outbounds(ctl: &Ctl, verb: Option<OutboundVerb>) -> Result<()> {
match verb.unwrap_or(OutboundVerb::List) {
OutboundVerb::List => {
let r = ctl.call(Request::Outbounds).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
let inv = &r["inventory"];
let pinned = inv["pinned"].as_str().unwrap_or("");
for t in inv["tags"].as_array().into_iter().flatten() {
let t = t.as_str().unwrap_or("");
let mut notes = Vec::new();
if t == pinned {
notes.push("pinned".to_owned());
}
if inv["disabled"].as_array().is_some_and(|d| d.iter().any(|x| x == t)) {
notes.push("disabled".into());
}
if let Some(h) = inv["detours"][t].as_str() {
notes.push(format!("through {h}"));
}
println!("{t:32} {:20} {}", inv["sources"][t].as_str().unwrap_or(""), notes.join(", "));
}
for (g, info) in inv["groups"].as_object().into_iter().flatten() {
let members: Vec<&str> = info["members"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
println!("{g:32} {:20} {}", format!("group, {}", info["strategy"].as_str().unwrap_or("")), members.join(" "));
}
}
OutboundVerb::Add { args, detour } => {
let (tag, link) = match args.as_slice() {
[link] => {
let link = read_arg(link)?;
(tag_for(&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?;
}
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?;
println!("removed {tag}");
}
OutboundVerb::Disable { tag } => {
ctl.call(Request::Disable { tag, disabled: true }).await?;
}
OutboundVerb::Enable { tag } => {
ctl.call(Request::Disable { tag, disabled: false }).await?;
}
OutboundVerb::Test { tags } => {
let r = ctl.call(Request::Test { tags }).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
for t in r.as_array().into_iter().flatten() {
match t["delay"].as_u64() {
Some(d) => println!("{:32} {d} ms", t["tag"].as_str().unwrap_or("")),
None => println!("{:32} {}", t["tag"].as_str().unwrap_or(""), t["error"].as_str().unwrap_or("failed")),
}
}
}
OutboundVerb::Link { tag } => {
let r = ctl.call(Request::Outbounds).await?;
match r["inventory"]["links"][&tag].as_str() {
Some(l) => println!("{l}"),
None => bail!("no link for '{tag}' (it has none, or you lack the secrets scope)"),
}
}
}
Ok(())
}
async fn subs(ctl: &Ctl, verb: Option<SubsVerb>) -> Result<()> {
match verb.unwrap_or(SubsVerb::List) {
SubsVerb::List => {
let c = ctl.call(Request::ConfigGet).await?;
for s in c["config"]["proxy"]["subscriptions"].as_array().into_iter().flatten() {
println!("{}", s["tag"].as_str().unwrap_or(""));
}
}
SubsVerb::Update { tag } => {
let r = ctl.call(Request::SubsUpdate { tag }).await?;
for s in r.as_array().into_iter().flatten() {
match s["links"].as_u64() {
Some(n) => println!("{}: {n} links", s["tag"].as_str().unwrap_or("")),
None => println!("{}: {}", s["tag"].as_str().unwrap_or(""), s["error"].as_str().unwrap_or("failed")),
}
}
}
SubsVerb::Add { args } => {
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)
}
[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?;
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?;
}
}
Ok(())
}
async fn rules(ctl: &Ctl, verb: Option<RulesVerb>) -> Result<()> {
match verb.unwrap_or(RulesVerb::List) {
RulesVerb::List => {
let c = ctl.call(Request::ConfigGet).await?;
for (i, r) in c["config"]["proxy"]["routing"]["rules"].as_array().into_iter().flatten().enumerate() {
let name = r["name"].as_str().map(str::to_owned).unwrap_or_else(|| format!("#{i}"));
let mut matches = Vec::new();
for (k, prefix) in [("domains", ""), ("ips", ""), ("geosites", "geosite:"), ("geoips", "geoip:"), ("ruleSets", "ruleset:"), ("processNames", "process:")] {
for v in r[k].as_array().into_iter().flatten() {
matches.push(format!("{prefix}{}", v.as_str().unwrap_or("")));
}
}
println!(
"{:4} {:20} -> {:16} {}{}",
r["priority"].as_i64().unwrap_or(100),
name,
r["outbound"].as_str().unwrap_or(""),
matches.join(" "),
if r["disabled"] == true { " (disabled)" } else { "" }
);
}
}
RulesVerb::Add { target, matches, name, priority } => {
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?;
}
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?;
}
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();
Ok(())
})
.await?;
ctl.call(Request::Start { unit: "proxy-suite-socks".into() }).await?;
}
ProxyVerb::Off => {
ctl.call(Request::Stop { unit: "proxy-suite-socks".into() }).await?;
}
ProxyVerb::Outbounds { verb } => outbounds(ctl, verb).await?,
ProxyVerb::Pin { tag, group } => {
ctl.call(Request::Pin { tag: Some(tag), group }).await?;
}
ProxyVerb::Unpin { group } => {
ctl.call(Request::Pin { tag: None, group }).await?;
}
ProxyVerb::Mode { mode: None } => {
let s = ctl.call(Request::Status).await?;
println!("{}", s["proxy"]["mode"].as_str().unwrap_or("default"));
}
ProxyVerb::Mode { mode } => {
ctl.call(Request::Mode { mode }).await?;
}
ProxyVerb::Subs { verb } => subs(ctl, verb).await?,
ProxyVerb::Rules { verb } => rules(ctl, verb).await?,
ProxyVerb::Rulesets { verb } => match verb.unwrap_or(RulesetsVerb::List) {
RulesetsVerb::List => {
let c = ctl.call(Request::ConfigGet).await?;
for (name, rs) in c["config"]["proxy"]["routing"]["ruleSets"].as_object().into_iter().flatten() {
println!("{name:24} {}", rs["url"].as_str().unwrap_or(""));
}
}
RulesetsVerb::Update => {
let r = ctl.call(Request::RuleSetsUpdate).await?;
for x in r.as_array().into_iter().flatten() {
println!("{:32} {}", x["tag"].as_str().unwrap_or(""), x["error"].as_str().unwrap_or("ok"));
}
}
},
ProxyVerb::Tun { verb } => match verb.unwrap_or(OnOff::Status) {
OnOff::Status => {
let s = ctl.call(Request::Status).await?;
println!("{}", if s["proxy"]["tun"] == true { "on" } else { "off" });
}
OnOff::On => {
ctl.call(Request::Start { unit: "proxy-suite-tun".into() }).await?;
}
OnOff::Off => {
ctl.call(Request::Stop { unit: "proxy-suite-tun".into() }).await?;
}
},
ProxyVerb::Config => ctl.print(&ctl.call(Request::RenderedConfig).await?),
}
Ok(())
}
async fn real_main() -> Result<()> {
let cli = Cli::parse();
let addr = match cli.socket {
Some(s) if cfg!(windows) => Address::Pipe(s),
Some(s) => Address::Unix(s.into()),
None => Address::default_for_platform(),
};
let ctl = Ctl { 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?);
}
}
Cmd::Proxy(p) => proxy(&ctl, p.verb).await?,
Cmd::Config { verb } => match verb {
ConfigVerb::Get => {
let c = ctl.call(Request::ConfigGet).await?;
ctl.print(&c["config"]);
}
ConfigVerb::Set { file } => {
let config = read_file_arg(&file)?;
let r = ctl.call(Request::ConfigSet { config, base: None }).await?;
println!("revision {}", r["revision"]);
}
ConfigVerb::Validate { file } => {
let r = ctl.call(Request::ConfigValidate { config: read_file_arg(&file)? }).await?;
let issues = r["issues"].as_array().cloned().unwrap_or_default();
if issues.is_empty() {
println!("valid");
}
for i in issues {
println!("{}: {}: {}", i["severity"].as_str().unwrap_or(""), i["path"].as_str().unwrap_or(""), i["message"].as_str().unwrap_or(""));
}
}
},
}
Ok(())
}
fn main() {
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().expect("a runtime");
if let Err(e) = rt.block_on(real_main()) {
eprintln!("proxy-ctl: {e}");
std::process::exit(1);
}
}
+189
View File
@@ -0,0 +1,189 @@
//! The whole stack, offline: a sing-box Shadowsocks server and a small web server on
//! loopback, the service in console mode with a fresh state directory, proxy-ctl adding the
//! server as an outbound, and a page fetched through the local proxy.
//!
//! Needs sing-box on PATH (the dev shell has it); skipped otherwise. Unix only: the Windows
//! side of the transport is a named pipe.
#![cfg(unix)]
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
const KEY: &str = "a2tra2tra2tra2tra2traw=="; // base64 of 16 'k's
fn free_port() -> u16 {
TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
}
struct Kill(Child);
impl Drop for Kill {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
fn service_binary() -> PathBuf {
let ctl = PathBuf::from(env!("CARGO_BIN_EXE_proxy-ctl"));
let dir = ctl.parent().unwrap();
let status = Command::new(env!("CARGO"))
.args(["build", "-q", "-p", "ps-service", "--bin", "proxy-suite-service"])
.status()
.unwrap();
assert!(status.success());
dir.join("proxy-suite-service")
}
fn ctl(socket: &Path, args: &[&str]) -> (bool, String) {
let out = Command::new(env!("CARGO_BIN_EXE_proxy-ctl")).arg("--socket").arg(socket).args(args).output().unwrap();
(out.status.success(), format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)))
}
/// GET http://<host>:<port>/ through a SOCKS5 proxy, with the name resolved by the proxy.
fn socks_get(proxy: u16, host: &str, port: u16) -> std::io::Result<String> {
let mut s = TcpStream::connect(("127.0.0.1", proxy))?;
s.set_read_timeout(Some(Duration::from_secs(10)))?;
s.write_all(&[5, 1, 0])?;
let mut buf = [0u8; 2];
s.read_exact(&mut buf)?;
let mut req = vec![5, 1, 0, 3, host.len() as u8];
req.extend_from_slice(host.as_bytes());
req.extend_from_slice(&port.to_be_bytes());
s.write_all(&req)?;
let mut reply = [0u8; 10];
s.read_exact(&mut reply)?;
if reply[1] != 0 {
return Err(std::io::Error::other(format!("SOCKS reply {}", reply[1])));
}
s.write_all(format!("GET / HTTP/1.0\r\nHost: {host}\r\n\r\n").as_bytes())?;
let mut body = String::new();
s.read_to_string(&mut body)?;
Ok(body)
}
fn wait_for(what: &str, timeout: Duration, mut check: impl FnMut() -> bool) {
let start = Instant::now();
while start.elapsed() < timeout {
if check() {
return;
}
std::thread::sleep(Duration::from_millis(250));
}
panic!("timed out waiting for {what}");
}
#[test]
fn a_page_through_the_whole_stack() {
if Command::new("sing-box").arg("version").output().is_err() {
eprintln!("sing-box is not on PATH: skipping");
return;
}
let dir = std::env::temp_dir().join(format!("ps-e2e-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let (ss_port, web_port, proxy_port, clash_port, test_port) = (free_port(), free_port(), free_port(), free_port(), free_port());
// The web server.
let web = TcpListener::bind(("127.0.0.1", web_port)).unwrap();
std::thread::spawn(move || {
for mut s in web.incoming().flatten() {
let mut buf = [0u8; 1024];
let _ = s.read(&mut buf);
let _ = s.write_all(b"HTTP/1.0 200 OK\r\nContent-Length: 19\r\n\r\nhello-through-proxy");
}
});
// The Shadowsocks server, which knows web.test as loopback.
let server_cfg = serde_json::json!({
"log": { "level": "warn" },
"dns": { "servers": [{ "type": "hosts", "tag": "hosts", "predefined": { "web.test": ["127.0.0.1"] } }] },
"inbounds": [{ "type": "shadowsocks", "tag": "ss-in", "listen": "127.0.0.1", "listen_port": ss_port,
"method": "2022-blake3-aes-128-gcm", "password": KEY }],
"outbounds": [{ "type": "direct", "tag": "direct" }],
"route": { "default_domain_resolver": "hosts", "final": "direct" },
});
std::fs::write(dir.join("server.json"), server_cfg.to_string()).unwrap();
let _server = Kill(Command::new("sing-box").args(["run", "-c"]).arg(dir.join("server.json")).stderr(Stdio::null()).spawn().unwrap());
// The service, with no outbound yet and nothing to download.
let state = dir.join("state");
std::fs::create_dir_all(&state).unwrap();
let config = serde_json::json!({
"proxy": {
"enable": true,
"listener": { "port": proxy_port },
"singBox": { "clashApiPort": clash_port, "testPort": test_port },
"routing": { "directRu": false },
},
});
std::fs::write(state.join("config.json"), config.to_string()).unwrap();
let socket = dir.join("api.sock");
let _service = Kill(
Command::new(service_binary())
.args(["--console", "--state-dir"])
.arg(&state)
.arg("--socket")
.arg(&socket)
.stderr(std::fs::File::create(dir.join("service.log")).unwrap())
.spawn()
.unwrap(),
);
wait_for("the service's API", Duration::from_secs(10), || ctl(&socket, &["status"]).0);
// proxy-ctl adds the server; the service renders, checks and starts sing-box.
let link = format!("ss://2022-blake3-aes-128-gcm:{}@127.0.0.1:{ss_port}#Test%20Server", KEY.replace('=', "%3D"));
let (ok, out) = ctl(&socket, &["proxy", "outbounds", "add", &link]);
assert!(ok, "{out}");
assert!(out.contains("added Test-Server"), "{out}");
let start = Instant::now();
while !ctl(&socket, &["status"]).1.contains("proxy: active") {
if start.elapsed() > Duration::from_secs(15) {
panic!(
"the proxy did not come up\nstatus:\n{}\nlogs:\n{}\nservice:\n{}",
ctl(&socket, &["status"]).1,
ctl(&socket, &["logs", "-n", "60"]).1,
std::fs::read_to_string(dir.join("service.log")).unwrap_or_default()
);
}
std::thread::sleep(Duration::from_millis(250));
}
let body = (0..20)
.find_map(|_| {
std::thread::sleep(Duration::from_millis(300));
socks_get(proxy_port, "web.test", web_port).ok()
})
.unwrap_or_else(|| {
panic!(
"no page through the proxy\nservice log:\n{}\nunit log:\n{}",
std::fs::read_to_string(dir.join("service.log")).unwrap_or_default(),
ctl(&socket, &["logs", "-n", "50"]).1
)
});
assert!(body.ends_with("hello-through-proxy"), "{body}");
// The inventory, a pin, and a route mode that sends everything direct, where web.test
// does not resolve.
let (_, list) = ctl(&socket, &["proxy", "outbounds"]);
assert!(list.contains("Test-Server") && list.contains("static"), "{list}");
assert!(ctl(&socket, &["proxy", "pin", "Test-Server"]).0);
assert!(ctl(&socket, &["status"]).1.contains("pinned to Test-Server"));
assert!(ctl(&socket, &["proxy", "mode", "all-bypass"]).0);
std::thread::sleep(Duration::from_secs(2));
assert!(socks_get(proxy_port, "web.test", web_port).map_or(true, |b| !b.ends_with("hello-through-proxy")));
assert!(ctl(&socket, &["proxy", "mode", "default"]).0);
// A bad edit is refused and changes nothing.
let (ok, out) = ctl(&socket, &["proxy", "rules", "add", "nowhere-real", "example.com"]);
assert!(!ok && out.contains("is not an outbound"), "{out}");
assert!(!ctl(&socket, &["proxy", "rules"]).1.contains("nowhere-real"));
// A good one goes in.
let (ok, out) = ctl(&socket, &["proxy", "rules", "add", "Test-Server", "example.com", "geoip:us", "process:Telegram.exe"]);
assert!(ok, "{out}");
assert!(ctl(&socket, &["proxy", "rules"]).1.contains("process:Telegram.exe"));
let _ = std::fs::remove_dir_all(&dir);
}