- zapret-presets: the presets of the installed zapret release and the one configured; proxy-ctl zapret presets. - tg-links: tg-ws-proxy's tg:// links (dd, and ee with a fake-TLS domain), as it prints them; they carry its secret, so the secrets scope. proxy-ctl tg link. No more reading them out of its log. - tools/dev-service.sh: the service on Linux with a demo outbound, for working on the app. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
642 lines
22 KiB
Rust
642 lines
22 KiB
Rust
//! proxy-ctl: upstream's command line, over the service's API.
|
|
|
|
use std::io::Read;
|
|
|
|
use anyhow::{Context, Result, bail};
|
|
use clap::{Args, Parser, Subcommand};
|
|
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)]
|
|
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,
|
|
},
|
|
/// DPI bypass: status, on, off, or the presets and the one to use.
|
|
Zapret {
|
|
#[command(subcommand)]
|
|
verb: Option<ZapretVerb>,
|
|
},
|
|
/// Telegram's WebSocket proxy (tg-ws-proxy).
|
|
Tg {
|
|
#[command(subcommand)]
|
|
verb: TgVerb,
|
|
},
|
|
/// The backend programs: what is installed, and installing them (administrator).
|
|
Components {
|
|
#[command(subcommand)]
|
|
verb: Option<ComponentsVerb>,
|
|
},
|
|
}
|
|
|
|
#[derive(Subcommand)]
|
|
enum TgVerb {
|
|
/// Its tg:// links, to open in Telegram.
|
|
Link,
|
|
}
|
|
|
|
#[derive(Subcommand)]
|
|
enum ZapretVerb {
|
|
Status,
|
|
On,
|
|
Off,
|
|
/// The presets of the installed release; the one in use is marked.
|
|
Presets,
|
|
/// Use this preset (zapret-discord-youtube), e.g. "general (ALT9)".
|
|
Preset { name: String },
|
|
/// Which game traffic to handle: all, tcp, udp or null.
|
|
GameFilter { filter: String },
|
|
}
|
|
|
|
#[derive(Subcommand)]
|
|
enum ComponentsVerb {
|
|
List,
|
|
/// Fetch, verify and install (all, or the named).
|
|
Install { names: Vec<String> },
|
|
}
|
|
|
|
#[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 {
|
|
client: Client,
|
|
json: bool,
|
|
}
|
|
|
|
impl Ctl {
|
|
async fn call(&self, req: Request) -> Result<Value> {
|
|
self.client.call(req).await
|
|
}
|
|
|
|
fn print(&self, v: &Value) {
|
|
println!("{}", serde_json::to_string_pretty(v).unwrap());
|
|
}
|
|
|
|
/// 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}");
|
|
}
|
|
if let Some(e) = &saved.apply_error {
|
|
eprintln!("saved, but not applied: {e}");
|
|
}
|
|
Ok(saved)
|
|
}
|
|
}
|
|
|
|
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"))
|
|
}
|
|
|
|
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, text) = match args.as_slice() {
|
|
[link] => {
|
|
let link = read_arg(link)?;
|
|
(edits::link_tag(&link), link)
|
|
}
|
|
[tag, link] => (tag.clone(), read_arg(link)?),
|
|
_ => bail!("usage: proxy outbounds add [tag] <link|->"),
|
|
};
|
|
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| edits::remove_outbound(c, &tag)).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)?;
|
|
(edits::subscription_tag(&url), url)
|
|
}
|
|
[tag, url] => (tag.clone(), read_arg(url)?),
|
|
_ => bail!("usage: proxy subs add [tag] <url|->"),
|
|
};
|
|
ctl.edit(|c| edits::add_subscription(c, &tag, &url)).await?;
|
|
println!("added {tag}; fetching it");
|
|
}
|
|
SubsVerb::Rm { tag } => {
|
|
ctl.edit(|c| edits::remove_subscription(c, &tag)).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...>");
|
|
}
|
|
ctl.edit(|c| edits::add_rule(c, &target, &matches, name.as_deref(), priority)).await?;
|
|
}
|
|
RulesVerb::Rm { name } => {
|
|
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?;
|
|
}
|
|
}
|
|
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| {
|
|
edits::set_proxy_enabled(c, true);
|
|
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.edit(|c| {
|
|
edits::set_tun_enabled(c, true);
|
|
Ok(())
|
|
})
|
|
.await?;
|
|
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 zapret(ctl: &Ctl, verb: Option<ZapretVerb>) -> Result<()> {
|
|
match verb.unwrap_or(ZapretVerb::Status) {
|
|
ZapretVerb::Status => {
|
|
let s = ctl.call(Request::Status).await?;
|
|
let z = &s["zapret"];
|
|
if ctl.json {
|
|
ctl.print(z);
|
|
} else if z["enabled"] == true {
|
|
println!("zapret: {} ({}, {})", z["state"].as_str().unwrap_or("?"), z["engine"].as_str().unwrap_or("?"), z["preset"].as_str().unwrap_or("?"));
|
|
} else {
|
|
println!("zapret: off");
|
|
}
|
|
}
|
|
v @ (ZapretVerb::On | ZapretVerb::Off) => {
|
|
let on = matches!(v, ZapretVerb::On);
|
|
ctl.edit(|c| {
|
|
edits::set_zapret_enabled(c, on);
|
|
Ok(())
|
|
})
|
|
.await?;
|
|
}
|
|
ZapretVerb::Presets => {
|
|
let r = ctl.call(Request::ZapretPresets).await?;
|
|
if ctl.json {
|
|
ctl.print(&r);
|
|
return Ok(());
|
|
}
|
|
let current = r["current"].as_str().unwrap_or("");
|
|
for p in r["presets"].as_array().into_iter().flatten().filter_map(Value::as_str) {
|
|
println!("{} {p}", if p == current { "*" } else { " " });
|
|
}
|
|
}
|
|
ZapretVerb::Preset { name } => {
|
|
ctl.edit(|c| {
|
|
edits::set_zapret_preset(c, &name);
|
|
Ok(())
|
|
})
|
|
.await?;
|
|
}
|
|
ZapretVerb::GameFilter { filter } => {
|
|
// 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(())
|
|
}
|
|
|
|
async fn components(ctl: &Ctl, verb: Option<ComponentsVerb>) -> Result<()> {
|
|
match verb.unwrap_or(ComponentsVerb::List) {
|
|
ComponentsVerb::List => {
|
|
let r = ctl.call(Request::Components).await?;
|
|
if ctl.json {
|
|
ctl.print(&r);
|
|
return Ok(());
|
|
}
|
|
for c in r.as_array().into_iter().flatten() {
|
|
let installed = c["installed"].as_str().unwrap_or("not installed");
|
|
let want = c["version"].as_str().unwrap_or("");
|
|
let note = if installed == want { "" } else { " (update with proxy-ctl components install)" };
|
|
println!("{:14} {:22} installed {installed}{note}", c["name"].as_str().unwrap_or(""), want);
|
|
}
|
|
}
|
|
ComponentsVerb::Install { names } => {
|
|
let r = ctl.call(Request::ComponentsInstall { names }).await?;
|
|
for c in r.as_array().into_iter().flatten() {
|
|
match c["error"].as_str() {
|
|
Some(e) => println!("{}: {e}", c["name"].as_str().unwrap_or("")),
|
|
None => println!("{} {} installed", c["name"].as_str().unwrap_or(""), c["version"].as_str().unwrap_or("")),
|
|
}
|
|
}
|
|
}
|
|
}
|
|
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 { 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 } => {
|
|
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?,
|
|
Cmd::Components { verb } => components(&ctl, verb).await?,
|
|
Cmd::Tg { verb: TgVerb::Link } => {
|
|
let r = ctl.call(Request::TgLinks).await?;
|
|
for l in r["links"].as_array().into_iter().flatten().filter_map(Value::as_str) {
|
|
println!("{l}");
|
|
}
|
|
}
|
|
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);
|
|
}
|
|
}
|