Files
proxy-suite-flake/windows/crates/ps-ctl/src/main.rs
T
faumarayandClaude Opus 5.5 803e18db9d windows: zapret2's 16 KB cutoff probe
Upstream's cutoff.nix and cutoff-probe.template.sh: z2k-detect (built from
z2k's pinned source for Windows, in zapret2-extras) finds the networks this
line cuts after ~16 KB, and with z2k's own strategies a whitelisted name per
network; z2k-tcp16.lua inside winws2 reads the maps (Z2K_TCP16_*, their
digest in the environment so a new map restarts winws2); what no name fixes
goes to the zapret-cutoff rule-set for the proxy (cutoff.proxyFallback).

Upstream keeps zapret2 off the probe with an nft cgroup rule. Here
z2k-detect is patched to dial from a local port range
(Z2K_TCP16_LOCAL_PORTS, 44000-47999, below Windows' dynamic range) and
winws2 gets --wf-raw-filter leaving that range alone; under the TUN the
probe and the service's own lookups of the line's network go direct.

Rounds as upstream's timer: 5 min after start, every 10 min, probing when
the line's network (ipinfo.io and ifconfig.co agreeing) changed or a day
passed. Request::ZapretCutoff, proxy-ctl zapret cutoff [probe], a card on
the DPI page. Verified live on a line that cuts (25 networks, a name for
each), the Windows z2k-detect under Wine, winws2 --dry-run and --wf-save
with the filter. gui-shot's scroll takes a count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 23:12:43 +03:00

1047 lines
38 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,
},
/// AmneziaWG profiles: the system-wide ones started and stopped.
Awg {
#[command(subcommand)]
verb: Option<AwgVerb>,
},
/// whitelist-bypass creators and joiners.
Wl {
#[command(subcommand)]
verb: Option<WlVerb>,
},
/// The backend programs: what is installed, and installing them (administrator).
Components {
#[command(subcommand)]
verb: Option<ComponentsVerb>,
},
/// Proxy Suite itself: whether a newer release is out, and installing it.
Update {
#[command(subcommand)]
verb: Option<UpdateVerb>,
},
}
#[derive(Subcommand)]
enum UpdateVerb {
/// This version, and a newer release if there is one.
Check,
/// Fetch the newest release's setup program, check it and run it: the service and the app
/// stop for a moment and start again, new.
Install,
}
#[derive(Subcommand)]
enum TgVerb {
/// Its tg:// links, to open in Telegram.
Link,
}
#[derive(Subcommand)]
enum AwgVerb {
/// Profiles and their state.
List,
/// Start a system-wide profile's tunnel.
On { profile: String },
/// Stop it.
Off { profile: String },
/// Its tunnel's log.
Log {
profile: String,
#[arg(short = 'n', long, default_value_t = 50)]
lines: usize,
},
}
#[derive(Subcommand)]
enum WlVerb {
/// Creators and joiners, and their state.
List,
/// The call a creator made, for its joiner.
Link { creator: String },
/// A creator's login: a cookies export (a file, or - for stdin); DION and Bitrix ask for
/// an email and password without one.
Auth { creator: String, file: Option<String> },
/// The call link a joiner joins (or - for stdin).
Join { joiner: String, link: String },
/// Start a new call, if the platform closed the old one.
New { creator: String },
/// Restart all of them, or the one named.
Restart { name: Option<String> },
}
#[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 },
/// zapret2's 16 KB cutoff probe: the networks this line cuts off, and the names that get
/// through (status), or probe the line now (probe).
Cutoff {
#[command(subcommand)]
verb: Option<CutoffVerb>,
},
}
#[derive(Subcommand)]
enum CutoffVerb {
Status,
/// Probe the line now: a few minutes, thousands of short direct connections.
Probe,
}
#[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,
/// autoProxy: what it routed and where; probing, learning, forgetting.
Auto {
#[command(subcommand)]
verb: Option<AutoVerb>,
},
}
#[derive(Subcommand)]
enum AutoVerb {
/// The routes learned, the exits, what waits.
List,
/// Probe a site (host, or host/path) through the exits, as autoProxy does.
Probe {
target: String,
/// Only these exits (comma-separated), in this order.
#[arg(long, value_delimiter = ',')]
exits: Option<Vec<String>>,
/// Whether this exit carries what direct reaches.
#[arg(long)]
via: Option<String>,
/// Try every exit, not only up to the first that reaches it.
#[arg(long)]
keep_going: bool,
},
/// Probe these hosts now, and route them if they need it.
Learn {
#[arg(required = true)]
hosts: Vec<String>,
},
/// Forget a domain's route: it is probed again when next dialled.
Forget { domain: String },
/// Forget everything learned.
Clear,
}
#[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())
}
}
/// A file's text, or stdin's for -.
fn read_arg_file(file: &str) -> Result<String> {
if file == "-" { read_arg("-") } else { std::fs::read_to_string(file).with_context(|| format!("reading {file}")) }
}
fn read_file_arg(file: &str) -> Result<Value> {
serde_json::from_str(&read_arg_file(file)?).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?),
ProxyVerb::Auto { verb } => auto(ctl, verb).await?,
}
Ok(())
}
async fn auto(ctl: &Ctl, verb: Option<AutoVerb>) -> Result<()> {
match verb.unwrap_or(AutoVerb::List) {
AutoVerb::List => {
let r = ctl.call(Request::AutoList).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
let state = match (r["enabled"] == true, r["running"] == true) {
(false, _) => "off (proxy.autoProxy.enable)",
(true, false) => "on, waiting for the local proxy",
(true, true) => "running",
};
println!("autoProxy: {state}");
if let Some(e) = r["egress"].as_str() {
println!(" egress {e}");
}
let domains = r["domains"].as_array().cloned().unwrap_or_default();
if domains.is_empty() {
println!(" nothing routed yet");
} else {
println!(" {:<32} {:<20} PROBED AS", "DOMAIN", "EXIT");
for d in &domains {
println!(" {:<32} {:<20} {}", d["domain"].as_str().unwrap_or(""), d["exit"].as_str().unwrap_or(""), d["host"].as_str().unwrap_or("-"));
}
}
for e in r["exits"].as_array().into_iter().flatten().filter(|e| e["bad"] == true) {
let by: Vec<&str> = e["badBy"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
let why = if by.is_empty() { format!("{} strike(s)", e["strikes"]) } else { by.join(", ") };
println!(" bad exit {} (probed last): {why}", e["tag"].as_str().unwrap_or(""));
}
let censored = r["censored"].as_array().map_or_else(|| r["censored"].as_u64().unwrap_or(0) as usize, Vec::len);
println!(" {} host(s) judged, {censored} left to zapret, {} waiting to be probed", r["hostsJudged"], r["backlog"]);
}
AutoVerb::Probe { target, exits, via, keep_going } => {
let r = ctl.call(Request::AutoProbe { target, exits, via: via.clone(), keep_going }).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
println!(" domain {}", r["domain"].as_str().unwrap_or(""));
let chosen = (r["exit"].as_str().unwrap_or(""), r["path"].as_str().unwrap_or(""));
println!(" exits");
for row in r["rows"].as_array().into_iter().flatten() {
let (tag, path) = (row["tag"].as_str().unwrap_or(""), row["path"].as_str().unwrap_or(""));
let f: ps_core::autoproxy::Fetch = serde_json::from_value(row["fetch"].clone()).unwrap_or_default();
let mark = if (tag, path) == chosen { " <- chosen" } else { "" };
println!(" {tag:<18} {path:<12} {:<44} {}{mark}", ps_core::autoproxy::describe(&f), row["judgement"].as_str().unwrap_or(""));
}
let verdict = r["verdict"].as_str().unwrap_or("");
match via {
Some(v) if verdict == "ok" => println!(" verdict {v} answers it as well as direct does - it can carry it"),
Some(v) => println!(" verdict {v} answers it worse than direct does"),
None => println!(" verdict {}", ps_core::autoproxy::verdict_text(verdict, r["exit"].as_str())),
}
}
AutoVerb::Learn { hosts } => {
let r = ctl.call(Request::AutoLearn { hosts }).await?;
println!("{} host(s) queued; the prober runs now (proxy-ctl logs proxy-suite-autoproxy)", r["queued"]);
}
AutoVerb::Forget { domain } => {
ctl.call(Request::AutoForget { domain: Some(domain.clone()) }).await?;
println!("forgot {domain}");
}
AutoVerb::Clear => {
ctl.call(Request::AutoForget { domain: None }).await?;
println!("forgot everything learned");
}
}
Ok(())
}
/// The cutoff probe's findings, as upstream's `proxy-ctl zapret cutoff` prints them.
fn print_cutoff(r: &Value) {
if let Some(n) = r["note"].as_str().filter(|n| !n.is_empty()) {
println!("Note: {n}");
}
let Some(ts) = r["probed"].as_u64() else {
println!("Not probed yet.");
return;
};
println!("Probed: {} from {}", ps_client::utc(ts), r["egress"].as_str().unwrap_or("?"));
let nets = r["networks"].as_array().cloned().unwrap_or_default();
if nets.is_empty() {
println!("Cutoff: none on this line");
return;
}
println!("Cutoff: {} network(s)", nets.len());
let fallback = if r["proxyFallback"] == true { "no name - proxy fallback" } else { "no name" };
for n in nets {
println!(" AS{:<8} {}", n["asn"].as_str().unwrap_or("?"), n["name"].as_str().unwrap_or(fallback));
}
}
async fn cutoff(ctl: &Ctl, verb: Option<CutoffVerb>) -> Result<()> {
let probe = matches!(verb, Some(CutoffVerb::Probe));
let mut r = ctl.call(Request::ZapretCutoff { probe }).await?;
if probe {
if !ctl.json {
println!("Probing this line; this takes a few minutes...");
}
// Until the round it asked for has begun and ended.
let mut began = false;
for _ in 0..1800 {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
r = ctl.call(Request::ZapretCutoff { probe: false }).await?;
let probing = r["probing"] == true;
began |= probing;
if began && !probing || !began && r["note"].as_str().is_some_and(|n| !n.is_empty() && !n.starts_with("probed")) {
break;
}
}
}
if ctl.json {
ctl.print(&r);
} else if r["enabled"] != true {
println!("The cutoff probe needs zapret.engine = \"zapret2\" with zapret2.cutoff.enable.");
} else {
print_cutoff(&r);
}
Ok(())
}
async fn zapret(ctl: &Ctl, verb: Option<ZapretVerb>) -> Result<()> {
match verb.unwrap_or(ZapretVerb::Status) {
ZapretVerb::Cutoff { verb } => return cutoff(ctl, verb).await,
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 update(ctl: &Ctl, verb: Option<UpdateVerb>) -> Result<()> {
match verb.unwrap_or(UpdateVerb::Check) {
UpdateVerb::Check => {
let r = ctl.call(Request::UpdateCheck).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
let current = r["current"].as_str().unwrap_or("?");
match r["available"].as_object() {
Some(a) => {
println!("Proxy Suite {current}; {} is out: {}", a["version"].as_str().unwrap_or("?"), a["page"].as_str().unwrap_or(""));
println!("Install it with: proxy-ctl update install");
}
None => println!("Proxy Suite {current} is the newest release."),
}
}
UpdateVerb::Install => {
let r = ctl.call(Request::UpdateInstall).await?;
println!("Installing Proxy Suite {}: the service stops for a moment and starts again.", r["version"].as_str().unwrap_or("?"));
}
}
Ok(())
}
async fn awg(ctl: &Ctl, verb: Option<AwgVerb>) -> Result<()> {
match verb.unwrap_or(AwgVerb::List) {
AwgVerb::List => {
let r = ctl.call(Request::AwgList).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
let profiles = r["profiles"].as_array().cloned().unwrap_or_default();
if profiles.is_empty() {
println!("No AmneziaWG profiles configured.");
return Ok(());
}
if r["enabled"] != true {
println!("AmneziaWG is off (amneziaWg.enable).");
}
println!(" {:<24} {:<12} {:<12} INTERFACE", "PROFILE", "KIND", "STATUS");
for p in profiles {
let kind = match p["kind"].as_str().unwrap_or("") {
"vpn" => "system VPN",
"userspace" => "outbound",
"singBox" => "outbound (WG)",
k => k,
};
println!(" {:<24} {:<12} {:<12} {}", p["name"].as_str().unwrap_or(""), kind, p["state"].as_str().unwrap_or(""), p["interface"].as_str().unwrap_or("-"));
}
}
AwgVerb::On { profile } => {
let r = ctl.call(Request::AwgSet { name: profile.clone(), on: true }).await?;
println!("{profile}: {}", r["state"].as_str().unwrap_or("?"));
}
AwgVerb::Off { profile } => {
let r = ctl.call(Request::AwgSet { name: profile.clone(), on: false }).await?;
println!("{profile}: {}", r["state"].as_str().unwrap_or("?"));
}
AwgVerb::Log { profile, lines } => {
let r = ctl.call(Request::AwgLog { name: profile, lines }).await?;
for l in r["lines"].as_array().into_iter().flatten().filter_map(Value::as_str) {
println!("{l}");
}
}
}
Ok(())
}
/// A login for the DION and Bitrix creators, which log in on their own from it.
fn password_login(platform: &str, name: &str) -> Result<String> {
let fields: &[&str] = match platform {
"dion" => &["email", "password"],
"bitrix" => &["email", "password", "portal"],
_ => bail!("{platform} logs in only in a browser: export its cookies from the desktop Creator, then: proxy-ctl wl auth {name} <file>"),
};
let mut login = serde_json::Map::new();
for field in fields {
let value = if *field == "password" {
rpassword::prompt_password("Password: ")?
} else {
eprint!("{}{}: ", field[..1].to_uppercase(), &field[1..]);
let mut line = String::new();
std::io::stdin().read_line(&mut line)?;
line.trim().to_owned()
};
let value = match *field {
"portal" => {
let portal = value.trim_end_matches('/');
if portal.contains("://") { portal.to_owned() } else { format!("https://{portal}") }
}
_ => value,
};
login.insert((*field).to_owned(), Value::String(value));
}
Ok(Value::Object(login).to_string())
}
async fn wl(ctl: &Ctl, verb: Option<WlVerb>) -> Result<()> {
let say = |r: &Value| println!("{}: {}", r["unit"].as_str().unwrap_or("?"), r["state"].as_str().unwrap_or("?"));
match verb.unwrap_or(WlVerb::List) {
WlVerb::List => {
let r = ctl.call(Request::WlList).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
let list = r.as_array().cloned().unwrap_or_default();
if list.is_empty() {
println!("No whitelist-bypass creators or joiners configured.");
return Ok(());
}
println!(" {:<16} {:<8} {:<10} STATUS", "NAME", "ROLE", "PLATFORM");
for w in list {
let f = |k: &str| w[k].as_str().unwrap_or("").to_owned();
println!(" {:<16} {:<8} {:<10} {}", f("name"), f("role"), f("platform"), f("state"));
}
}
WlVerb::Link { creator } => {
let r = ctl.call(Request::WlLink { name: creator }).await?;
println!("{}", r["link"].as_str().unwrap_or(""));
}
WlVerb::Auth { creator, file } => {
let login = match file {
Some(f) => {
let text = read_arg_file(&f)?;
serde_json::from_str::<Value>(&text).context("not a cookies export, not valid JSON")?;
text
}
None => {
let list = ctl.call(Request::WlList).await?;
let platform = list
.as_array()
.into_iter()
.flatten()
.find(|w| w["name"] == creator.as_str() && w["role"] == "creator")
.and_then(|w| w["platform"].as_str().map(str::to_owned))
.with_context(|| format!("no whitelist-bypass creator '{creator}'"))?;
password_login(&platform, &creator)?
}
};
say(&ctl.call(Request::WlAuth { name: creator, login }).await?);
}
WlVerb::Join { joiner, link } => {
let link = read_arg(&link)?;
say(&ctl.call(Request::WlJoin { name: joiner, link: link.trim().to_owned() }).await?);
}
WlVerb::New { creator } => {
say(&ctl.call(Request::WlNew { name: creator.clone() }).await?);
println!("Its joiner needs the new call: proxy-ctl wl link {creator}");
}
WlVerb::Restart { name } => {
let list = ctl.call(Request::WlList).await?;
let units: Vec<String> = list
.as_array()
.into_iter()
.flatten()
.filter(|w| name.as_deref().is_none_or(|n| w["name"] == n))
.map(|w| format!("proxy-suite-wb-{}-{}", w["role"].as_str().unwrap_or(""), w["name"].as_str().unwrap_or("")))
.collect();
if units.is_empty() {
bail!("no such whitelist-bypass creator or joiner");
}
ctl.call(Request::Restart { units }).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::Wl { verb } => wl(&ctl, verb).await?,
Cmd::Awg { verb } => awg(&ctl, verb).await?,
Cmd::Update { verb } => update(&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);
}
}