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:
1 parent
918cdc9a75
commit
41c8ed4406
25 files changed
+5411
-7
No files matched your search
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user