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
Generated
+1825
-3
File diff suppressed because it is too large.
Load diff
+14
-1
@@ -1,6 +1,6 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["crates/ps-core"]
|
||||
members = ["crates/ps-core", "crates/ps-ipc", "crates/ps-service", "crates/ps-ctl"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
@@ -18,3 +18,16 @@ thiserror = "2"
|
||||
percent-encoding = "2"
|
||||
ipnet = "2"
|
||||
indexmap = { version = "2", features = ["serde"] }
|
||||
tokio = { version = "1.54", features = ["rt-multi-thread", "macros", "net", "io-util", "process", "time", "sync", "fs", "signal"] }
|
||||
clap = { version = "4.6", features = ["derive"] }
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "socks", "json", "stream", "http2", "query"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
windows-service = "0.8"
|
||||
windows-sys = "0.61"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
rand = "0.9"
|
||||
sha2 = "0.10"
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
ps-core = { path = "crates/ps-core" }
|
||||
ps-ipc = { path = "crates/ps-ipc" }
|
||||
@@ -158,11 +158,14 @@ impl Default for AutoProxy {
|
||||
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
|
||||
pub struct SingBoxOptions {
|
||||
pub clash_api_port: u16,
|
||||
/// Windows only: the loopback listener `proxy-ctl proxy outbounds test` reaches each
|
||||
/// outbound through. Upstream fixes it at 18537.
|
||||
pub test_port: u16,
|
||||
}
|
||||
|
||||
impl Default for SingBoxOptions {
|
||||
fn default() -> Self {
|
||||
Self { clash_api_port: 9090 }
|
||||
Self { clash_api_port: 9090, test_port: 18537 }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -565,7 +565,9 @@ fn ports(cfg: &Config, v: &mut Issues) {
|
||||
if p.backend.runs_sing_box() {
|
||||
claim(p.sing_box.clash_api_port, "proxy.singBox.clashApiPort".into(), v);
|
||||
}
|
||||
claim(derived::ports::OUTBOUND_TEST, "the outbound test listener".into(), v);
|
||||
if p.backend.runs_sing_box() {
|
||||
claim(p.sing_box.test_port, "proxy.singBox.testPort".into(), v);
|
||||
}
|
||||
}
|
||||
if cfg.tor.enable {
|
||||
claim(cfg.tor.socks_port, "tor.socksPort".into(), v);
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
//! Time spans as the options write them: systemd's ("1d", "6h", "1h 30min") and Go's
|
||||
//! ("3m", "15s", "1m30s", "500ms").
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
/// A span such as "1d", "6h 30m", "1m30s" or "500ms". A bare number is seconds.
|
||||
pub fn parse(text: &str) -> Option<Duration> {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if let Ok(secs) = text.parse::<f64>() {
|
||||
return (secs >= 0.0).then(|| Duration::from_secs_f64(secs));
|
||||
}
|
||||
let mut total = 0f64;
|
||||
let mut rest = text;
|
||||
while !rest.is_empty() {
|
||||
rest = rest.trim_start();
|
||||
let num_len = rest.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(rest.len());
|
||||
if num_len == 0 {
|
||||
return None;
|
||||
}
|
||||
let value: f64 = rest[..num_len].parse().ok()?;
|
||||
rest = &rest[num_len..];
|
||||
let unit_len = rest.find(|c: char| !c.is_ascii_alphabetic()).unwrap_or(rest.len());
|
||||
let unit = &rest[..unit_len];
|
||||
rest = &rest[unit_len..];
|
||||
let factor = match unit {
|
||||
"ns" => 1e-9,
|
||||
"us" | "µs" => 1e-6,
|
||||
"ms" | "msec" => 1e-3,
|
||||
"s" | "sec" | "second" | "seconds" | "" => 1.0,
|
||||
"m" | "min" | "minute" | "minutes" => 60.0,
|
||||
"h" | "hr" | "hour" | "hours" => 3600.0,
|
||||
"d" | "day" | "days" => 86400.0,
|
||||
"w" | "week" | "weeks" => 604800.0,
|
||||
_ => return None,
|
||||
};
|
||||
total += value * factor;
|
||||
}
|
||||
Some(Duration::from_secs_f64(total))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn both_spellings_read() {
|
||||
assert_eq!(parse("1d"), Some(Duration::from_secs(86400)));
|
||||
assert_eq!(parse("6h 30min"), Some(Duration::from_secs(6 * 3600 + 1800)));
|
||||
assert_eq!(parse("1m30s"), Some(Duration::from_secs(90)));
|
||||
assert_eq!(parse("500ms"), Some(Duration::from_millis(500)));
|
||||
assert_eq!(parse("45"), Some(Duration::from_secs(45)));
|
||||
assert_eq!(parse("soon"), None);
|
||||
assert_eq!(parse("3x"), None);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
pub mod config;
|
||||
pub mod derived;
|
||||
pub mod duration;
|
||||
pub mod links;
|
||||
pub mod render;
|
||||
pub mod wg;
|
||||
@@ -104,7 +104,7 @@ pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec<String>)
|
||||
inbounds.push(mixed);
|
||||
// The test listener `proxy-ctl proxy outbounds test` dials each outbound through, by the
|
||||
// Clash API's switching of its selector.
|
||||
let mut test_in = json!({ "type": "mixed", "tag": "proxy-suite-test-in", "listen": "127.0.0.1", "listen_port": ports::OUTBOUND_TEST });
|
||||
let mut test_in = json!({ "type": "mixed", "tag": "proxy-suite-test-in", "listen": "127.0.0.1", "listen_port": p.sing_box.test_port });
|
||||
if let Some(users) = &users {
|
||||
test_in["users"] = users.clone();
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "ps-ipc"
|
||||
description = "Proxy Suite for Windows: the service's API and its transport"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio.workspace = true
|
||||
thiserror.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { workspace = true, features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Security",
|
||||
"Win32_Security_Authorization",
|
||||
"Win32_System_Pipes",
|
||||
"Win32_System_Threading",
|
||||
"Win32_System_SystemServices",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true }
|
||||
@@ -0,0 +1,115 @@
|
||||
//! The service's API: what proxy-ctl and the app ask, what it answers, and how the two
|
||||
//! reach each other. One JSON request per line, answered by one JSON response per line (a
|
||||
//! log follow answers with many, up to a final one).
|
||||
//!
|
||||
//! On Windows the transport is the named pipe `\\.\pipe\proxy-suite`, whose security
|
||||
//! descriptor admits SYSTEM, Administrators and (with `userControl`) the interactive user.
|
||||
//! Elsewhere it is a Unix socket, so the whole stack runs on Linux for development.
|
||||
|
||||
pub mod transport;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
/// The pipe on Windows.
|
||||
pub const PIPE_NAME: &str = r"\\.\pipe\proxy-suite";
|
||||
|
||||
/// Who is asking, as the transport established it (never as the client claims).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Peer {
|
||||
/// An administrator (elevated on Windows, root elsewhere): every scope, and the
|
||||
/// admin-only options.
|
||||
pub admin: bool,
|
||||
/// The account, for the log.
|
||||
pub user: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "kebab-case")]
|
||||
pub enum Request {
|
||||
/// Units, their state, the proxy's mode.
|
||||
Status,
|
||||
/// The configuration. Secrets (links, passwords) need the `secrets` scope.
|
||||
ConfigGet,
|
||||
/// Replaces the whole configuration, if it is valid and `base` (a revision from
|
||||
/// `config-get`) is still current.
|
||||
ConfigSet { config: Value, base: Option<u64> },
|
||||
/// Checks a configuration without taking it.
|
||||
ConfigValidate { config: Value },
|
||||
/// Runtime state: pins, disabled outbounds, the route mode.
|
||||
StateGet,
|
||||
Pin { tag: Option<String>, group: Option<String> },
|
||||
Disable { tag: String, disabled: bool },
|
||||
Mode { mode: Option<String> },
|
||||
/// What the proxy runs: tags, sources, groups, the pick.
|
||||
Outbounds,
|
||||
/// The backend configs as rendered last. Secrets scope.
|
||||
RenderedConfig,
|
||||
Restart { units: Vec<String> },
|
||||
Start { unit: String },
|
||||
Stop { unit: String },
|
||||
/// The last `lines` of a unit's log (every unit's, interleaved, without one); `follow`
|
||||
/// keeps the answer open with each new line.
|
||||
Logs { unit: Option<String>, lines: usize, follow: bool },
|
||||
/// Refetch subscriptions (all, or one).
|
||||
SubsUpdate { tag: Option<String> },
|
||||
/// Refetch rule sets and geodata.
|
||||
RuleSetsUpdate,
|
||||
/// Latency of outbounds through the Clash API.
|
||||
Test { tags: Vec<String> },
|
||||
/// Components: what is installed, what the manifest wants.
|
||||
Components,
|
||||
/// Fetch and install components (all wanted, or the named ones).
|
||||
ComponentsInstall { names: Vec<String> },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Response {
|
||||
pub ok: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub error: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Value::is_null")]
|
||||
pub data: Value,
|
||||
/// More responses follow (a log follow).
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub more: bool,
|
||||
}
|
||||
|
||||
impl Response {
|
||||
pub fn ok(data: Value) -> Self {
|
||||
Self { ok: true, error: None, data, more: false }
|
||||
}
|
||||
|
||||
pub fn err(message: impl Into<String>) -> Self {
|
||||
Self { ok: false, error: Some(message.into()), data: Value::Null, more: false }
|
||||
}
|
||||
|
||||
pub fn partial(data: Value) -> Self {
|
||||
Self { ok: true, error: None, data, more: true }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum IpcError {
|
||||
#[error("cannot reach the Proxy Suite service ({0}); is it running?")]
|
||||
Connect(std::io::Error),
|
||||
#[error("the service closed the connection")]
|
||||
Closed,
|
||||
#[error("{0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("bad message: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn requests_read_as_upstream_verbs() {
|
||||
let r: Request = serde_json::from_str(r#"{"op":"pin","tag":"nl","group":null}"#).unwrap();
|
||||
assert_eq!(r, Request::Pin { tag: Some("nl".into()), group: None });
|
||||
let s = serde_json::to_string(&Request::Logs { unit: None, lines: 50, follow: true }).unwrap();
|
||||
assert_eq!(s, r#"{"op":"logs","unit":null,"lines":50,"follow":true}"#);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
//! Line-delimited JSON over a named pipe (Windows) or a Unix socket (elsewhere).
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, ReadHalf, WriteHalf};
|
||||
|
||||
use crate::{IpcError, Peer, Request, Response};
|
||||
|
||||
/// Where the service listens.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Address {
|
||||
Pipe(String),
|
||||
Unix(PathBuf),
|
||||
}
|
||||
|
||||
impl Address {
|
||||
/// `PROXY_SUITE_SOCKET` if set, else the platform's default.
|
||||
pub fn default_for_platform() -> Self {
|
||||
if let Ok(s) = std::env::var("PROXY_SUITE_SOCKET") {
|
||||
return if cfg!(windows) { Address::Pipe(s) } else { Address::Unix(s.into()) };
|
||||
}
|
||||
if cfg!(windows) {
|
||||
Address::Pipe(crate::PIPE_NAME.into())
|
||||
} else {
|
||||
Address::Unix(std::env::temp_dir().join("proxy-suite.sock"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
trait Stream: AsyncRead + AsyncWrite + Send + Unpin + 'static {}
|
||||
impl<T: AsyncRead + AsyncWrite + Send + Unpin + 'static> Stream for T {}
|
||||
|
||||
/// One connection, either end.
|
||||
pub struct Conn {
|
||||
reader: BufReader<ReadHalf<Box<dyn Stream>>>,
|
||||
writer: WriteHalf<Box<dyn Stream>>,
|
||||
identity: Identity,
|
||||
}
|
||||
|
||||
enum Identity {
|
||||
Client,
|
||||
#[cfg(unix)]
|
||||
Unix(Option<u32>),
|
||||
#[cfg(windows)]
|
||||
Pipe(isize),
|
||||
}
|
||||
|
||||
impl Conn {
|
||||
fn new(stream: Box<dyn Stream>, identity: Identity) -> Self {
|
||||
let (r, w) = tokio::io::split(stream);
|
||||
Self { reader: BufReader::new(r), writer: w, identity }
|
||||
}
|
||||
|
||||
/// The next message, or `None` once the other end closed.
|
||||
pub async fn read_json<T: DeserializeOwned>(&mut self) -> Result<Option<T>, IpcError> {
|
||||
let mut line = String::new();
|
||||
// A request is a configuration at most: 16 MiB is far past any.
|
||||
let n = (&mut self.reader).take(16 * 1024 * 1024).read_line(&mut line).await?;
|
||||
if n == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(serde_json::from_str(line.trim_end())?))
|
||||
}
|
||||
|
||||
pub async fn write_json<T: Serialize>(&mut self, value: &T) -> Result<(), IpcError> {
|
||||
let mut line = serde_json::to_vec(value)?;
|
||||
line.push(b'\n');
|
||||
self.writer.write_all(&line).await?;
|
||||
self.writer.flush().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Who the other end is. On Windows the client must have sent its first message: only
|
||||
/// then can the server impersonate it.
|
||||
pub fn peer(&self) -> Peer {
|
||||
match &self.identity {
|
||||
Identity::Client => Peer { admin: false, user: "client".into() },
|
||||
#[cfg(unix)]
|
||||
Identity::Unix(uid) => Peer {
|
||||
admin: *uid == Some(0),
|
||||
user: uid.map_or_else(|| "unknown".into(), |u| format!("uid {u}")),
|
||||
},
|
||||
#[cfg(windows)]
|
||||
Identity::Pipe(handle) => windows::peer(*handle),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The listening end.
|
||||
pub struct Server {
|
||||
#[cfg(unix)]
|
||||
listener: tokio::net::UnixListener,
|
||||
#[cfg(windows)]
|
||||
next: tokio::net::windows::named_pipe::NamedPipeServer,
|
||||
#[cfg(windows)]
|
||||
name: String,
|
||||
#[cfg(windows)]
|
||||
sddl: String,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// Listens on `address`. `interactive`: whether signed-in users may connect, besides
|
||||
/// SYSTEM and Administrators (`userControl.enable`); on Unix the socket's mode does it.
|
||||
pub fn bind(address: &Address, interactive: bool) -> std::io::Result<Self> {
|
||||
match address {
|
||||
#[cfg(unix)]
|
||||
Address::Unix(path) => {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ = std::fs::remove_file(path);
|
||||
let listener = tokio::net::UnixListener::bind(path)?;
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(if interactive { 0o666 } else { 0o600 }))?;
|
||||
Ok(Self { listener })
|
||||
}
|
||||
#[cfg(windows)]
|
||||
Address::Pipe(name) => {
|
||||
let sddl = windows::sddl(interactive);
|
||||
let next = windows::create(name, &sddl, true)?;
|
||||
Ok(Self { next, name: name.clone(), sddl })
|
||||
}
|
||||
#[allow(unreachable_patterns)]
|
||||
_ => Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "this address does not exist on this platform")),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn accept(&mut self) -> std::io::Result<Conn> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let (stream, _) = self.listener.accept().await?;
|
||||
let uid = stream.peer_cred().ok().map(|c| c.uid());
|
||||
Ok(Conn::new(Box::new(stream), Identity::Unix(uid)))
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
self.next.connect().await?;
|
||||
let connected = std::mem::replace(&mut self.next, windows::create(&self.name, &self.sddl, false)?);
|
||||
let handle = connected.as_raw_handle() as isize;
|
||||
Ok(Conn::new(Box::new(connected), Identity::Pipe(handle)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn connect(address: &Address) -> Result<Conn, IpcError> {
|
||||
match address {
|
||||
#[cfg(unix)]
|
||||
Address::Unix(path) => {
|
||||
let stream = tokio::net::UnixStream::connect(path).await.map_err(IpcError::Connect)?;
|
||||
Ok(Conn::new(Box::new(stream), Identity::Client))
|
||||
}
|
||||
#[cfg(windows)]
|
||||
Address::Pipe(name) => {
|
||||
use tokio::net::windows::named_pipe::ClientOptions;
|
||||
let client = loop {
|
||||
match ClientOptions::new().open(name) {
|
||||
Ok(c) => break c,
|
||||
// Every instance busy: the next is a moment away.
|
||||
Err(e) if e.raw_os_error() == Some(231) => tokio::time::sleep(std::time::Duration::from_millis(50)).await,
|
||||
Err(e) => return Err(IpcError::Connect(e)),
|
||||
}
|
||||
};
|
||||
Ok(Conn::new(Box::new(client), Identity::Client))
|
||||
}
|
||||
#[allow(unreachable_patterns)]
|
||||
_ => Err(IpcError::Connect(std::io::Error::new(std::io::ErrorKind::Unsupported, "no such transport here"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// One request, its one answer.
|
||||
pub async fn call(address: &Address, request: &Request) -> Result<Response, IpcError> {
|
||||
let mut conn = connect(address).await?;
|
||||
conn.write_json(request).await?;
|
||||
conn.read_json().await?.ok_or(IpcError::Closed)
|
||||
}
|
||||
|
||||
/// One request, every answer until the last (a log follow), each handed to `each`.
|
||||
pub async fn stream(address: &Address, request: &Request, mut each: impl FnMut(Response) -> bool) -> Result<(), IpcError> {
|
||||
let mut conn = connect(address).await?;
|
||||
conn.write_json(request).await?;
|
||||
while let Some(response) = conn.read_json::<Response>().await? {
|
||||
let more = response.more;
|
||||
if !each(response) || !more {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows {
|
||||
use std::ffi::c_void;
|
||||
use std::ptr::null_mut;
|
||||
|
||||
use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions};
|
||||
use windows_sys::Win32::Foundation::{CloseHandle, FALSE, HANDLE, LocalFree, TRUE};
|
||||
use windows_sys::Win32::Security::Authorization::{
|
||||
ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
|
||||
};
|
||||
use windows_sys::Win32::Security::{
|
||||
CheckTokenMembership, CreateWellKnownSid, GetTokenInformation, LookupAccountSidW, RevertToSelf,
|
||||
SECURITY_ATTRIBUTES, SID_NAME_USE, TOKEN_QUERY, TOKEN_USER, TokenUser, WinBuiltinAdministratorsSid,
|
||||
};
|
||||
use windows_sys::Win32::System::Pipes::ImpersonateNamedPipeClient;
|
||||
use windows_sys::Win32::System::Threading::{GetCurrentThread, OpenThreadToken};
|
||||
|
||||
use crate::Peer;
|
||||
|
||||
/// SYSTEM and Administrators get everything; the interactive user read and write.
|
||||
pub fn sddl(interactive: bool) -> String {
|
||||
let mut s = String::from("D:P(A;;GA;;;SY)(A;;GA;;;BA)");
|
||||
if interactive {
|
||||
s.push_str("(A;;GRGW;;;IU)");
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn wide(s: &str) -> Vec<u16> {
|
||||
s.encode_utf16().chain(std::iter::once(0)).collect()
|
||||
}
|
||||
|
||||
pub fn create(name: &str, sddl: &str, first: bool) -> std::io::Result<NamedPipeServer> {
|
||||
let sddl_w = wide(sddl);
|
||||
let mut descriptor: *mut c_void = null_mut();
|
||||
// SAFETY: a NUL-terminated string in, a descriptor LocalFree'd below out.
|
||||
let ok = unsafe {
|
||||
ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl_w.as_ptr(), SDDL_REVISION_1, &mut descriptor, null_mut())
|
||||
};
|
||||
if ok == 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
let mut attrs = SECURITY_ATTRIBUTES {
|
||||
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
|
||||
lpSecurityDescriptor: descriptor,
|
||||
bInheritHandle: FALSE,
|
||||
};
|
||||
// SAFETY: attrs and the descriptor it points at outlive the call.
|
||||
let server = unsafe {
|
||||
ServerOptions::new()
|
||||
// The first instance: nobody else may have made the pipe first (squatting).
|
||||
.first_pipe_instance(first)
|
||||
.reject_remote_clients(true)
|
||||
.create_with_security_attributes_raw(name, &mut attrs as *mut _ as *mut c_void)
|
||||
};
|
||||
// SAFETY: allocated by ConvertStringSecurityDescriptorToSecurityDescriptorW.
|
||||
unsafe { LocalFree(descriptor) };
|
||||
server
|
||||
}
|
||||
|
||||
/// The client of the pipe, impersonated to read its token: an administrator only when
|
||||
/// its token holds Administrators enabled (elevated), never as it claims.
|
||||
pub fn peer(pipe: isize) -> Peer {
|
||||
let unknown = Peer { admin: false, user: "unknown".into() };
|
||||
// SAFETY: the pipe handle is live for the connection; the impersonation is undone
|
||||
// before anything else runs on this thread.
|
||||
unsafe {
|
||||
if ImpersonateNamedPipeClient(pipe as HANDLE) == 0 {
|
||||
return unknown;
|
||||
}
|
||||
let mut token: HANDLE = null_mut();
|
||||
let opened = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &mut token);
|
||||
RevertToSelf();
|
||||
if opened == 0 {
|
||||
return unknown;
|
||||
}
|
||||
let mut sid = [0u8; 68];
|
||||
let mut size = sid.len() as u32;
|
||||
let mut admin = 0;
|
||||
if CreateWellKnownSid(WinBuiltinAdministratorsSid, null_mut(), sid.as_mut_ptr() as *mut c_void, &mut size) != 0 {
|
||||
CheckTokenMembership(token, sid.as_mut_ptr() as *mut c_void, &mut admin);
|
||||
}
|
||||
let user = token_user(token).unwrap_or_else(|| "unknown".into());
|
||||
CloseHandle(token);
|
||||
Peer { admin: admin != 0, user }
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn token_user(token: HANDLE) -> Option<String> {
|
||||
let mut buf = vec![0u8; 256];
|
||||
let mut len = 0u32;
|
||||
// SAFETY: buf is as long as said.
|
||||
if unsafe { GetTokenInformation(token, TokenUser, buf.as_mut_ptr() as *mut c_void, buf.len() as u32, &mut len) } == 0 {
|
||||
return None;
|
||||
}
|
||||
let user = unsafe { &*(buf.as_ptr() as *const TOKEN_USER) };
|
||||
let mut name = vec![0u16; 256];
|
||||
let mut domain = vec![0u16; 256];
|
||||
let (mut nlen, mut dlen) = (name.len() as u32, domain.len() as u32);
|
||||
let mut kind: SID_NAME_USE = 0;
|
||||
// SAFETY: the SID points into buf, which is alive; the buffers are as long as said.
|
||||
let ok = unsafe {
|
||||
LookupAccountSidW(null_mut(), user.User.Sid, name.as_mut_ptr(), &mut nlen, domain.as_mut_ptr(), &mut dlen, &mut kind)
|
||||
};
|
||||
if ok == 0 {
|
||||
return None;
|
||||
}
|
||||
let name = String::from_utf16_lossy(&name[..nlen as usize]);
|
||||
let domain = String::from_utf16_lossy(&domain[..dlen as usize]);
|
||||
Some(if domain.is_empty() { name } else { format!("{domain}\\{name}") })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_round_trip_over_a_socket() {
|
||||
let path = std::env::temp_dir().join(format!("ps-ipc-test-{}.sock", std::process::id()));
|
||||
let address = Address::Unix(path.clone());
|
||||
let mut server = Server::bind(&address, true).unwrap();
|
||||
let handle = tokio::spawn(async move {
|
||||
let mut conn = server.accept().await.unwrap();
|
||||
let req: Request = conn.read_json().await.unwrap().unwrap();
|
||||
let peer = conn.peer();
|
||||
conn.write_json(&Response::ok(serde_json::json!({ "echo": req, "uid": peer.user }))).await.unwrap();
|
||||
});
|
||||
let resp = call(&address, &Request::Status).await.unwrap();
|
||||
assert!(resp.ok);
|
||||
assert_eq!(resp.data["echo"]["op"], "status");
|
||||
assert!(resp.data["uid"].as_str().unwrap().starts_with("uid "));
|
||||
handle.await.unwrap();
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
[package]
|
||||
name = "ps-service"
|
||||
description = "Proxy Suite for Windows: the service that runs the backends"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "proxy-suite-service"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
ps-core.workspace = true
|
||||
ps-ipc.workspace = true
|
||||
anyhow.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio.workspace = true
|
||||
clap.workspace = true
|
||||
reqwest.workspace = true
|
||||
rustls.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
rand.workspace = true
|
||||
sha2.workspace = true
|
||||
zip.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-service.workspace = true
|
||||
windows-sys = { workspace = true, features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Security",
|
||||
"Win32_System_JobObjects",
|
||||
"Win32_System_Threading",
|
||||
] }
|
||||
@@ -0,0 +1,488 @@
|
||||
//! The API: who may do what, and doing it.
|
||||
|
||||
use ps_core::config::{Config, Issue, Scope, Severity, privileged_changes, validate};
|
||||
use ps_core::render::RouteMode;
|
||||
use ps_ipc::transport::{Conn, Server};
|
||||
use ps_ipc::{Peer, Request, Response};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::service::{self, Shared};
|
||||
|
||||
/// What stands in for a secret a caller may not read. Sent back unchanged, it keeps the
|
||||
/// value it hides.
|
||||
pub const REDACTED: &str = "\u{2022}\u{2022}\u{2022}redacted\u{2022}\u{2022}\u{2022}";
|
||||
|
||||
/// Option paths holding secrets (`*`: any key or list entry).
|
||||
const SECRET_PATHS: [&str; 19] = [
|
||||
"proxy.outbounds.*.url",
|
||||
"proxy.outbounds.*.singBoxJson",
|
||||
"proxy.outbounds.*.xrayJson",
|
||||
"proxy.subscriptions.*.url",
|
||||
"proxy.listener.auth.password",
|
||||
"amneziaWg.profiles.*.config",
|
||||
"amneziaWg.profiles.*.vpn",
|
||||
"amneziaWg.profiles.*.settings.privateKey",
|
||||
"amneziaWg.profiles.*.settings.peers.*.presharedKey",
|
||||
"amneziaWg.profiles.*.settings.obfuscation.headerProtectionKey",
|
||||
"warp.config",
|
||||
"warp.devices.*.config",
|
||||
"tgWsProxy.secret",
|
||||
"inbounds.users.*.uuid",
|
||||
"inbounds.users.*.password",
|
||||
"inbounds.listeners.*.serverPassword",
|
||||
"inbounds.listeners.*.reality.privateKey",
|
||||
"inbounds.listeners.*.hysteria.salamander.password",
|
||||
"inbounds.listeners.*.xrayJson",
|
||||
];
|
||||
|
||||
fn redact_at(value: &mut Value, path: &[&str]) {
|
||||
let Some((head, rest)) = path.split_first() else {
|
||||
if !value.is_null() {
|
||||
*value = REDACTED.into();
|
||||
}
|
||||
return;
|
||||
};
|
||||
match value {
|
||||
Value::Object(map) => {
|
||||
if *head == "*" {
|
||||
map.values_mut().for_each(|v| redact_at(v, rest));
|
||||
} else if let Some(v) = map.get_mut(*head) {
|
||||
redact_at(v, rest);
|
||||
}
|
||||
}
|
||||
Value::Array(list) if *head == "*" => list.iter_mut().for_each(|v| redact_at(v, rest)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn redact(config: &Config) -> Value {
|
||||
let mut v = serde_json::to_value(config).expect("the config serializes");
|
||||
for p in SECRET_PATHS {
|
||||
redact_at(&mut v, &p.split('.').collect::<Vec<_>>());
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The entry of `old` a list entry of `new` stands for: by its tag or name, else its index.
|
||||
fn counterpart<'a>(old: &'a [Value], new: &Value, index: usize) -> Option<&'a Value> {
|
||||
for key in ["tag", "name"] {
|
||||
if let Some(id) = new.get(key).filter(|v| v.is_string()) {
|
||||
return old.iter().find(|o| o.get(key) == Some(id));
|
||||
}
|
||||
}
|
||||
old.get(index)
|
||||
}
|
||||
|
||||
fn unredact_at(new: &mut Value, old: Option<&Value>, path: &[&str]) {
|
||||
let Some((head, rest)) = path.split_first() else {
|
||||
if new.as_str() == Some(REDACTED) {
|
||||
*new = old.cloned().unwrap_or(Value::Null);
|
||||
}
|
||||
return;
|
||||
};
|
||||
match new {
|
||||
Value::Object(map) => {
|
||||
let old_map = old.and_then(Value::as_object);
|
||||
if *head == "*" {
|
||||
for (k, v) in map.iter_mut() {
|
||||
unredact_at(v, old_map.and_then(|m| m.get(k)), rest);
|
||||
}
|
||||
} else if let Some(v) = map.get_mut(*head) {
|
||||
unredact_at(v, old_map.and_then(|m| m.get(*head)), rest);
|
||||
}
|
||||
}
|
||||
Value::Array(list) if *head == "*" => {
|
||||
let old_list = old.and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]);
|
||||
for (i, v) in list.iter_mut().enumerate() {
|
||||
let o = counterpart(old_list, v, i).cloned();
|
||||
unredact_at(v, o.as_ref(), rest);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// `new` with every placeholder replaced by the value it hid in `old`.
|
||||
pub fn unredact(new: &mut Value, old: &Config) {
|
||||
let old = serde_json::to_value(old).expect("the config serializes");
|
||||
for p in SECRET_PATHS {
|
||||
unredact_at(new, Some(&old), &p.split('.').collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `peer` may use `scope`, under `cfg.userControl`.
|
||||
fn allowed(cfg: &Config, peer: &Peer, scope: Option<Scope>) -> Result<(), String> {
|
||||
if peer.admin {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(scope) = scope else { return Ok(()) };
|
||||
let uc = &cfg.user_control;
|
||||
if !uc.enable {
|
||||
return Err("this needs an administrator (userControl is off)".into());
|
||||
}
|
||||
if uc.scopes.is_empty() || uc.scopes.contains(&scope) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("this needs the {scope:?} scope, which userControl does not give").to_lowercase())
|
||||
}
|
||||
}
|
||||
|
||||
fn scope_of(req: &Request) -> Option<Scope> {
|
||||
match req {
|
||||
Request::ConfigSet { .. } => Some(Scope::Config),
|
||||
Request::Pin { .. } | Request::Mode { .. } | Request::RuleSetsUpdate => Some(Scope::Routing),
|
||||
Request::Disable { .. } | Request::SubsUpdate { .. } | Request::Test { .. } => Some(Scope::Outbounds),
|
||||
Request::RenderedConfig => Some(Scope::Secrets),
|
||||
Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn has_secrets(cfg: &Config, peer: &Peer) -> bool {
|
||||
allowed(cfg, peer, Some(Scope::Secrets)).is_ok()
|
||||
}
|
||||
|
||||
fn issues_json(issues: &[Issue]) -> Value {
|
||||
serde_json::to_value(issues).unwrap()
|
||||
}
|
||||
|
||||
/// Serves the API until the process ends.
|
||||
pub async fn serve(mut server: Server, shared: Shared) {
|
||||
loop {
|
||||
match server.accept().await {
|
||||
Ok(conn) => {
|
||||
let shared = shared.clone();
|
||||
tokio::spawn(async move { connection(conn, shared).await });
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("accepting a client: {e}");
|
||||
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn connection(mut conn: Conn, shared: Shared) {
|
||||
loop {
|
||||
let req: Request = match conn.read_json().await {
|
||||
Ok(Some(r)) => r,
|
||||
Ok(None) => return,
|
||||
Err(e) => {
|
||||
let _ = conn.write_json(&Response::err(format!("bad request: {e}"))).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
let peer = conn.peer();
|
||||
if let Request::Logs { unit, lines, follow: true } = &req {
|
||||
follow_logs(&mut conn, &shared, unit.clone(), *lines).await;
|
||||
return;
|
||||
}
|
||||
let resp = handle(req, &peer, &shared).await;
|
||||
if conn.write_json(&resp).await.is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn follow_logs(conn: &mut Conn, shared: &Shared, unit: Option<String>, lines: usize) {
|
||||
let (backlog, mut feed) = {
|
||||
let s = shared.lock().await;
|
||||
(s.sup.tail(unit.as_deref(), lines), s.sup.subscribe())
|
||||
};
|
||||
for line in backlog {
|
||||
if conn.write_json(&Response::partial(json!(line))).await.is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
loop {
|
||||
match feed.recv().await {
|
||||
Ok(line) if unit.as_ref().is_none_or(|u| *u == line.unit) => {
|
||||
if conn.write_json(&Response::partial(json!(line))).await.is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
|
||||
Err(_) => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
|
||||
{
|
||||
let s = shared.lock().await;
|
||||
if let Err(e) = allowed(s.cfg(), peer, scope_of(&req)) {
|
||||
return Response::err(e);
|
||||
}
|
||||
}
|
||||
match req {
|
||||
Request::Status => Response::ok(shared.lock().await.status()),
|
||||
|
||||
Request::ConfigGet => {
|
||||
let s = shared.lock().await;
|
||||
let config = if has_secrets(s.cfg(), peer) { serde_json::to_value(s.cfg()).unwrap() } else { redact(s.cfg()) };
|
||||
Response::ok(json!({ "config": config, "revision": s.store.revision, "redacted": !has_secrets(s.cfg(), peer) }))
|
||||
}
|
||||
|
||||
Request::ConfigValidate { config } => match serde_json::from_value::<Config>(config) {
|
||||
Ok(cfg) => Response::ok(json!({ "issues": issues_json(&validate(&cfg)) })),
|
||||
Err(e) => Response::err(format!("not a configuration: {e}")),
|
||||
},
|
||||
|
||||
Request::ConfigSet { mut config, base } => {
|
||||
let mut s = shared.lock().await;
|
||||
if let Some(base) = base {
|
||||
if base != s.store.revision {
|
||||
return Response::err(format!(
|
||||
"the configuration changed since revision {base} (now {}): read it again",
|
||||
s.store.revision
|
||||
));
|
||||
}
|
||||
}
|
||||
unredact(&mut config, s.cfg());
|
||||
let new: Config = match serde_json::from_value(config) {
|
||||
Ok(c) => c,
|
||||
Err(e) => return Response::err(format!("not a configuration: {e}")),
|
||||
};
|
||||
let issues = validate(&new);
|
||||
if issues.iter().any(|i| i.severity == Severity::Error) {
|
||||
return Response { ok: false, error: Some("the configuration has errors".into()), data: json!({ "issues": issues_json(&issues) }), more: false };
|
||||
}
|
||||
if !peer.admin {
|
||||
let privileged = privileged_changes(s.cfg(), &new);
|
||||
if !privileged.is_empty() {
|
||||
return Response {
|
||||
ok: false,
|
||||
error: Some(format!("only an administrator may change {}", privileged.join(", "))),
|
||||
data: json!({ "privileged": privileged }),
|
||||
more: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
let subs_before: Vec<String> = s.cfg().proxy.subscriptions.iter().map(|x| x.tag.clone()).collect();
|
||||
if let Err(e) = s.store.save_config(new) {
|
||||
return Response::err(format!("cannot save the configuration: {e}"));
|
||||
}
|
||||
tracing::info!("configuration revision {} set by {}", s.store.revision, peer.user);
|
||||
let new_subs: Vec<String> =
|
||||
s.cfg().proxy.subscriptions.iter().map(|x| x.tag.clone()).filter(|t| !subs_before.contains(t)).collect();
|
||||
let applied = s.apply().await;
|
||||
let revision = s.store.revision;
|
||||
drop(s);
|
||||
// A new subscription is fetched at once, as upstream fetches on first start.
|
||||
for tag in new_subs {
|
||||
let shared = shared.clone();
|
||||
tokio::spawn(async move { service::update_subscriptions(&shared, Some(&tag)).await });
|
||||
}
|
||||
{
|
||||
let shared = shared.clone();
|
||||
tokio::spawn(async move { service::update_rule_sets(&shared, true).await });
|
||||
}
|
||||
Response::ok(json!({
|
||||
"revision": revision,
|
||||
"issues": issues_json(&issues),
|
||||
"applied": applied.as_ref().map(|_| true).unwrap_or(false),
|
||||
"error": applied.err().map(|e| e.to_string()),
|
||||
}))
|
||||
}
|
||||
|
||||
Request::StateGet => Response::ok(serde_json::to_value(&shared.lock().await.store.state).unwrap()),
|
||||
|
||||
Request::Pin { tag, group } => {
|
||||
let mut s = shared.lock().await;
|
||||
match group {
|
||||
Some(g) => match tag {
|
||||
Some(t) => {
|
||||
s.store.state.group_pins.insert(g, t);
|
||||
}
|
||||
None => {
|
||||
s.store.state.group_pins.remove(&g);
|
||||
}
|
||||
},
|
||||
None => s.store.state.pin = tag,
|
||||
}
|
||||
finish_state(&mut s).await
|
||||
}
|
||||
|
||||
Request::Disable { tag, disabled } => {
|
||||
let mut s = shared.lock().await;
|
||||
s.store.state.disabled.retain(|t| *t != tag);
|
||||
if disabled {
|
||||
s.store.state.disabled.push(tag);
|
||||
}
|
||||
finish_state(&mut s).await
|
||||
}
|
||||
|
||||
Request::Mode { mode } => {
|
||||
let mut s = shared.lock().await;
|
||||
s.store.state.route_mode = match mode.as_deref() {
|
||||
None | Some("default") => None,
|
||||
Some(m) => match serde_json::from_value::<RouteMode>(json!(m)) {
|
||||
Ok(m) => Some(m),
|
||||
Err(_) => return Response::err(format!("unknown mode '{m}': default, whitelist, blacklist, all-proxy or all-bypass")),
|
||||
},
|
||||
};
|
||||
finish_state(&mut s).await
|
||||
}
|
||||
|
||||
Request::Outbounds => {
|
||||
let s = shared.lock().await;
|
||||
let secrets = has_secrets(s.cfg(), peer);
|
||||
match &s.last {
|
||||
Some(r) => {
|
||||
let mut inv = serde_json::to_value(&r.inventory).unwrap();
|
||||
if !secrets {
|
||||
inv["links"] = json!({});
|
||||
}
|
||||
Response::ok(json!({ "inventory": inv, "warnings": r.warnings }))
|
||||
}
|
||||
None => Response::err(s.last_error.clone().unwrap_or_else(|| "the proxy is not running".into())),
|
||||
}
|
||||
}
|
||||
|
||||
Request::RenderedConfig => {
|
||||
let s = shared.lock().await;
|
||||
match &s.last {
|
||||
Some(r) => Response::ok(json!({ "sing-box": r.sing_box, "xray": r.xray })),
|
||||
None => Response::err("nothing rendered yet"),
|
||||
}
|
||||
}
|
||||
|
||||
Request::Restart { units } => {
|
||||
let mut s = shared.lock().await;
|
||||
let names = if units.is_empty() { s.sup.names() } else { units };
|
||||
let mut missing = Vec::new();
|
||||
for n in &names {
|
||||
if !s.sup.restart(n) {
|
||||
missing.push(n.clone());
|
||||
}
|
||||
}
|
||||
if missing.is_empty() { Response::ok(json!({ "restarted": names })) } else { Response::err(format!("no such unit: {}", missing.join(", "))) }
|
||||
}
|
||||
|
||||
Request::Start { unit } | Request::Stop { unit } if unit != service::SOCKS_UNIT && unit != "proxy-suite-tun" => {
|
||||
Response::err(format!("unit '{unit}' cannot be started or stopped on its own"))
|
||||
}
|
||||
|
||||
Request::Start { unit } => {
|
||||
let mut s = shared.lock().await;
|
||||
if unit == "proxy-suite-tun" {
|
||||
if !s.cfg().proxy.tun.enable {
|
||||
return Response::err("the global TUN is off in the configuration (proxy.tun.enable)");
|
||||
}
|
||||
s.tun = true;
|
||||
}
|
||||
s.proxy_on = true;
|
||||
applied(s.apply().await)
|
||||
}
|
||||
|
||||
Request::Stop { unit } => {
|
||||
let mut s = shared.lock().await;
|
||||
if unit == "proxy-suite-tun" {
|
||||
s.tun = false;
|
||||
} else {
|
||||
s.proxy_on = false;
|
||||
}
|
||||
applied(s.apply().await)
|
||||
}
|
||||
|
||||
Request::Logs { unit, lines, .. } => {
|
||||
let s = shared.lock().await;
|
||||
Response::ok(json!(s.sup.tail(unit.as_deref(), lines)))
|
||||
}
|
||||
|
||||
Request::SubsUpdate { tag } => {
|
||||
let results = service::update_subscriptions(shared, tag.as_deref()).await;
|
||||
Response::ok(json!(results.into_iter().map(|(t, r)| match r {
|
||||
Ok(n) => json!({ "tag": t, "links": n }),
|
||||
Err(e) => json!({ "tag": t, "error": e }),
|
||||
}).collect::<Vec<_>>()))
|
||||
}
|
||||
|
||||
Request::RuleSetsUpdate => {
|
||||
let results = service::update_rule_sets(shared, false).await;
|
||||
Response::ok(json!(results.into_iter().map(|(t, r)| match r {
|
||||
Ok(()) => json!({ "tag": t }),
|
||||
Err(e) => json!({ "tag": t, "error": e }),
|
||||
}).collect::<Vec<_>>()))
|
||||
}
|
||||
|
||||
Request::Test { tags } => {
|
||||
let (clash, tags, url) = {
|
||||
let s = shared.lock().await;
|
||||
let Some(r) = &s.last else { return Response::err("the proxy is not running") };
|
||||
let tags = if tags.is_empty() { r.inventory.exits.clone() } else { tags };
|
||||
(
|
||||
crate::clash::Clash::new(s.cfg().proxy.sing_box.clash_api_port, &s.store.secrets.clash_secret),
|
||||
tags,
|
||||
s.cfg().proxy.url_test.url.clone(),
|
||||
)
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for t in tags {
|
||||
out.push(match clash.delay(&t, &url, 5000).await {
|
||||
Ok(ms) => json!({ "tag": t, "delay": ms }),
|
||||
Err(e) => json!({ "tag": t, "error": e.to_string() }),
|
||||
});
|
||||
}
|
||||
Response::ok(json!(out))
|
||||
}
|
||||
|
||||
Request::Components | Request::ComponentsInstall { .. } => Response::err("the component manager is not there yet"),
|
||||
}
|
||||
}
|
||||
|
||||
fn applied(r: anyhow::Result<()>) -> Response {
|
||||
match r {
|
||||
Ok(()) => Response::ok(Value::Null),
|
||||
Err(e) => Response::err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn finish_state(s: &mut tokio::sync::MutexGuard<'_, service::Service>) -> Response {
|
||||
if let Err(e) = s.store.save_state() {
|
||||
return Response::err(format!("cannot save the state: {e}"));
|
||||
}
|
||||
applied(s.apply().await)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ps_core::config::Outbound;
|
||||
|
||||
#[test]
|
||||
fn redaction_round_trips_by_tag() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.proxy.outbounds = vec![
|
||||
Outbound { tag: "a".into(), url: Some("hy2://secret-a@a:443".into()), ..Default::default() },
|
||||
Outbound { tag: "b".into(), url: Some("hy2://secret-b@b:443".into()), ..Default::default() },
|
||||
];
|
||||
cfg.proxy.listener.auth.password = Some("pw".into());
|
||||
let mut shown = redact(&cfg);
|
||||
assert_eq!(shown["proxy"]["outbounds"][0]["url"], REDACTED);
|
||||
assert_eq!(shown["proxy"]["listener"]["auth"]["password"], REDACTED);
|
||||
// The client reorders and adds one; the hidden values follow their tags.
|
||||
let list = shown["proxy"]["outbounds"].as_array_mut().unwrap();
|
||||
list.swap(0, 1);
|
||||
list.push(json!({ "tag": "c", "url": "hy2://new@c:443" }));
|
||||
unredact(&mut shown, &cfg);
|
||||
let back: Config = serde_json::from_value(shown).unwrap();
|
||||
assert_eq!(back.proxy.outbounds[0].url.as_deref(), Some("hy2://secret-b@b:443"));
|
||||
assert_eq!(back.proxy.outbounds[1].url.as_deref(), Some("hy2://secret-a@a:443"));
|
||||
assert_eq!(back.proxy.outbounds[2].url.as_deref(), Some("hy2://new@c:443"));
|
||||
assert_eq!(back.proxy.listener.auth.password.as_deref(), Some("pw"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scopes_follow_user_control() {
|
||||
let mut cfg = Config::default();
|
||||
let user = Peer { admin: false, user: "u".into() };
|
||||
assert!(allowed(&cfg, &user, Some(Scope::Routing)).is_ok());
|
||||
cfg.user_control.scopes = vec![Scope::Routing];
|
||||
assert!(allowed(&cfg, &user, Some(Scope::Routing)).is_ok());
|
||||
assert!(allowed(&cfg, &user, Some(Scope::Config)).is_err());
|
||||
cfg.user_control.enable = false;
|
||||
assert!(allowed(&cfg, &user, Some(Scope::Routing)).is_err());
|
||||
assert!(allowed(&cfg, &Peer { admin: true, user: "a".into() }, Some(Scope::Config)).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! sing-box's Clash API on loopback: what selectors pick, and outbound latency.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde_json::Value;
|
||||
|
||||
pub struct Clash {
|
||||
base: String,
|
||||
secret: String,
|
||||
http: reqwest::Client,
|
||||
}
|
||||
|
||||
fn encode(segment: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for b in segment.bytes() {
|
||||
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
|
||||
out.push(b as char);
|
||||
} else {
|
||||
out.push_str(&format!("%{b:02X}"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Clash {
|
||||
pub fn new(port: u16, secret: &str) -> Self {
|
||||
let http = reqwest::Client::builder()
|
||||
.no_proxy()
|
||||
.timeout(Duration::from_secs(20))
|
||||
.build()
|
||||
.expect("an HTTP client");
|
||||
Self { base: format!("http://127.0.0.1:{port}"), secret: secret.to_owned(), http }
|
||||
}
|
||||
|
||||
async fn get(&self, path: &str) -> Result<Value> {
|
||||
let resp = self.http.get(format!("{}{path}", self.base)).bearer_auth(&self.secret).send().await?;
|
||||
let status = resp.status();
|
||||
let body: Value = resp.json().await.unwrap_or(Value::Null);
|
||||
if !status.is_success() {
|
||||
bail!("{}", body["message"].as_str().unwrap_or(status.as_str()));
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
/// Every proxy (outbound or group) with what a selector holds now.
|
||||
pub async fn proxies(&self) -> Result<Value> {
|
||||
self.get("/proxies").await.map(|v| v["proxies"].clone())
|
||||
}
|
||||
|
||||
/// What `group` (a selector or urltest) uses now.
|
||||
pub async fn current(&self, group: &str) -> Result<Option<String>> {
|
||||
let v = self.get(&format!("/proxies/{}", encode(group))).await?;
|
||||
Ok(v["now"].as_str().map(str::to_owned))
|
||||
}
|
||||
|
||||
/// Switches the selector `group` to `tag`, live.
|
||||
pub async fn select(&self, group: &str, tag: &str) -> Result<()> {
|
||||
let resp = self
|
||||
.http
|
||||
.put(format!("{}/proxies/{}", self.base, encode(group)))
|
||||
.bearer_auth(&self.secret)
|
||||
.json(&serde_json::json!({ "name": tag }))
|
||||
.send()
|
||||
.await
|
||||
.context("the Clash API")?;
|
||||
if !resp.status().is_success() {
|
||||
let body: Value = resp.json().await.unwrap_or(Value::Null);
|
||||
bail!("cannot switch {group} to {tag}: {}", body["message"].as_str().unwrap_or("refused"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The delay to `url` through `tag`, in milliseconds.
|
||||
pub async fn delay(&self, tag: &str, url: &str, timeout_ms: u32) -> Result<u32> {
|
||||
let resp = self
|
||||
.http
|
||||
.get(format!("{}/proxies/{}/delay", self.base, encode(tag)))
|
||||
.bearer_auth(&self.secret)
|
||||
.query(&[("url", url), ("timeout", &timeout_ms.to_string())])
|
||||
.send()
|
||||
.await?;
|
||||
let status = resp.status();
|
||||
let body: Value = resp.json().await.unwrap_or(Value::Null);
|
||||
if !status.is_success() {
|
||||
bail!("{}", body["message"].as_str().unwrap_or("timed out"));
|
||||
}
|
||||
body["delay"].as_u64().map(|d| d as u32).context("no delay in the answer")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//! Where the backend programs are.
|
||||
//!
|
||||
//! The service installs each into `bin\<component>\` (the component manager); a program
|
||||
//! found there wins. Elsewhere (development on Linux) the one on PATH is taken.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub struct Components {
|
||||
bin: PathBuf,
|
||||
}
|
||||
|
||||
impl Components {
|
||||
pub fn new(bin: PathBuf) -> Self {
|
||||
Self { bin }
|
||||
}
|
||||
|
||||
/// The program `name` (without `.exe`) of `component`.
|
||||
pub fn find(&self, component: &str, name: &str) -> Option<PathBuf> {
|
||||
let file = if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() };
|
||||
let installed = self.bin.join(component).join(&file);
|
||||
if installed.is_file() {
|
||||
return Some(installed);
|
||||
}
|
||||
let path = std::env::var_os("PATH")?;
|
||||
std::env::split_paths(&path).map(|dir| dir.join(&file)).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
pub fn sing_box(&self) -> Option<PathBuf> {
|
||||
self.find("sing-box", "sing-box")
|
||||
}
|
||||
|
||||
pub fn xray(&self) -> Option<PathBuf> {
|
||||
self.find("xray", "xray")
|
||||
}
|
||||
|
||||
pub fn bin_dir(&self) -> &Path {
|
||||
&self.bin
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
//! Fetching subscriptions and rule sets: through the local proxy when it runs, else (or
|
||||
//! when that fails, with `killSwitch.directFallbacks`) directly. Redirects follow upstream's
|
||||
//! rule: http and https only, never down to http, never nearer to this host.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use ps_core::links::subscription::{self, MAX_SUBSCRIPTION_BYTES, USER_AGENT, url_parts};
|
||||
|
||||
/// How to reach the network for a fetch.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Route {
|
||||
Direct,
|
||||
/// The local proxy's mixed listener, with its login.
|
||||
Proxy { port: u16, login: Option<(String, String)> },
|
||||
}
|
||||
|
||||
fn client(route: &Route) -> Result<reqwest::Client> {
|
||||
let policy = reqwest::redirect::Policy::custom(|attempt| {
|
||||
let from = attempt.previous().last().map(|u| u.as_str().to_owned()).unwrap_or_default();
|
||||
let to = attempt.url().as_str().to_owned();
|
||||
if attempt.previous().len() > 10 {
|
||||
return attempt.error("too many redirects");
|
||||
}
|
||||
match (url_parts::split(&from), url_parts::split(&to)) {
|
||||
(Ok(f), Ok(t)) => match subscription::redirect_allowed(&f, &t) {
|
||||
Ok(()) => attempt.follow(),
|
||||
Err(why) => attempt.error(why),
|
||||
},
|
||||
_ => attempt.error("a redirect to an unreadable URL"),
|
||||
}
|
||||
});
|
||||
let mut b = reqwest::Client::builder()
|
||||
.user_agent(USER_AGENT)
|
||||
.redirect(policy)
|
||||
.connect_timeout(Duration::from_secs(15))
|
||||
.timeout(Duration::from_secs(60));
|
||||
b = match route {
|
||||
Route::Direct => b.no_proxy(),
|
||||
Route::Proxy { port, login } => {
|
||||
// socks5h: the proxy resolves the name, as it would for an app.
|
||||
let url = match login {
|
||||
Some((u, p)) => format!("socks5h://{u}:{p}@127.0.0.1:{port}"),
|
||||
None => format!("socks5h://127.0.0.1:{port}"),
|
||||
};
|
||||
b.proxy(reqwest::Proxy::all(url)?)
|
||||
}
|
||||
};
|
||||
Ok(b.build()?)
|
||||
}
|
||||
|
||||
/// The body of `url`, at most `limit` bytes. The error never quotes the URL: it is a secret.
|
||||
pub async fn get(url: &str, route: &Route, limit: usize) -> Result<Vec<u8>> {
|
||||
let scheme = url_parts::split(url).map(|u| u.scheme).unwrap_or_default();
|
||||
if scheme != "http" && scheme != "https" {
|
||||
bail!("the URL must be http:// or https://");
|
||||
}
|
||||
let mut resp = client(route)?.get(url).send().await.map_err(|e| anyhow::anyhow!(describe(&e)))?;
|
||||
if !resp.status().is_success() {
|
||||
bail!("the server answered {}", resp.status());
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = resp.chunk().await.map_err(|e| anyhow::anyhow!(describe(&e)))? {
|
||||
body.extend_from_slice(&chunk);
|
||||
if body.len() > limit {
|
||||
bail!("the answer is larger than {limit} bytes");
|
||||
}
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
/// A reqwest error without the URL it carries.
|
||||
fn describe(e: &reqwest::Error) -> String {
|
||||
let kind = if e.is_timeout() {
|
||||
"timed out"
|
||||
} else if e.is_connect() {
|
||||
"cannot connect"
|
||||
} else if e.is_redirect() {
|
||||
"a redirect was refused"
|
||||
} else if e.is_request() {
|
||||
"the request failed"
|
||||
} else {
|
||||
"the transfer failed"
|
||||
};
|
||||
let mut source = std::error::Error::source(e);
|
||||
let mut detail = String::new();
|
||||
while let Some(s) = source {
|
||||
detail = s.to_string();
|
||||
source = s.source();
|
||||
}
|
||||
if detail.is_empty() { kind.into() } else { format!("{kind}: {detail}") }
|
||||
}
|
||||
|
||||
/// A subscription's links: fetched by the first route that works.
|
||||
pub async fn subscription(url: &str, routes: &[Route]) -> Result<Vec<String>> {
|
||||
let mut last = None;
|
||||
for route in routes {
|
||||
match get(url, route, MAX_SUBSCRIPTION_BYTES).await {
|
||||
Ok(body) => {
|
||||
let lines = subscription::decode_subscription(&body);
|
||||
if lines.is_empty() {
|
||||
bail!("the subscription is empty");
|
||||
}
|
||||
return Ok(lines);
|
||||
}
|
||||
Err(e) => last = Some(e),
|
||||
}
|
||||
}
|
||||
Err(last.unwrap_or_else(|| anyhow::anyhow!("no way to fetch it")))
|
||||
}
|
||||
|
||||
/// A rule set to `dest`, written atomically.
|
||||
pub async fn rule_set(url: &str, routes: &[Route], dest: &std::path::Path) -> Result<()> {
|
||||
let mut last = None;
|
||||
for route in routes {
|
||||
match get(url, route, 64 * 1024 * 1024).await {
|
||||
Ok(body) => {
|
||||
crate::paths::write_atomic(dest, &body).with_context(|| format!("writing {}", dest.display()))?;
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => last = Some(e),
|
||||
}
|
||||
}
|
||||
Err(last.unwrap_or_else(|| anyhow::anyhow!("no way to fetch it")))
|
||||
}
|
||||
|
||||
/// The domain-only copy of a source rule set, for DNS rules: sing-box refuses address
|
||||
/// matches there.
|
||||
pub fn domain_only(source: &serde_json::Value) -> serde_json::Value {
|
||||
const DOMAIN_KEYS: [&str; 4] = ["domain", "domain_suffix", "domain_keyword", "domain_regex"];
|
||||
let rules: Vec<serde_json::Value> = source["rules"]
|
||||
.as_array()
|
||||
.map(|rules| {
|
||||
rules
|
||||
.iter()
|
||||
.filter_map(|r| {
|
||||
let obj = r.as_object()?;
|
||||
let kept: serde_json::Map<String, serde_json::Value> =
|
||||
obj.iter().filter(|(k, _)| DOMAIN_KEYS.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
(!kept.is_empty()).then_some(serde_json::Value::Object(kept))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
serde_json::json!({ "version": source["version"].as_u64().unwrap_or(1), "rules": rules })
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
//! A Windows Job Object that kills every child with the service: a crash of the service
|
||||
//! must not leave sing-box or winws running, holding the TUN or WinDivert.
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::ptr::null;
|
||||
|
||||
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
|
||||
use windows_sys::Win32::System::JobObjects::{
|
||||
AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
|
||||
JobObjectExtendedLimitInformation, SetInformationJobObject,
|
||||
};
|
||||
|
||||
pub struct Job(HANDLE);
|
||||
|
||||
// SAFETY: a job handle may be used from any thread.
|
||||
unsafe impl Send for Job {}
|
||||
unsafe impl Sync for Job {}
|
||||
|
||||
impl Job {
|
||||
pub fn new() -> std::io::Result<Self> {
|
||||
// SAFETY: an anonymous job; the handle is closed in Drop.
|
||||
unsafe {
|
||||
let job = CreateJobObjectW(null(), null());
|
||||
if job.is_null() {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = std::mem::zeroed();
|
||||
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
let ok = SetInformationJobObject(
|
||||
job,
|
||||
JobObjectExtendedLimitInformation,
|
||||
&info as *const _ as *const c_void,
|
||||
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
|
||||
);
|
||||
if ok == 0 {
|
||||
let err = std::io::Error::last_os_error();
|
||||
CloseHandle(job);
|
||||
return Err(err);
|
||||
}
|
||||
Ok(Self(job))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle(&self) -> isize {
|
||||
self.0 as isize
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Job {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: ours, closed once.
|
||||
unsafe { CloseHandle(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts a process into the job. A failure is logged, not fatal: the process still runs.
|
||||
pub fn assign(job: isize, process: isize) {
|
||||
// SAFETY: both handles are live: the job for the service's life, the process until it
|
||||
// has been waited on.
|
||||
if unsafe { AssignProcessToJobObject(job as HANDLE, process as HANDLE) } == 0 {
|
||||
tracing::warn!("cannot add a child to the job: {}", std::io::Error::last_os_error());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! proxy-suite-service: runs the backends, keeps the configuration, serves the API.
|
||||
//!
|
||||
//! As a Windows service it is started by the Service Control Manager (`install` registers
|
||||
//! it); `--console` runs it in the foreground, which is also how it runs off Windows.
|
||||
|
||||
mod api;
|
||||
mod clash;
|
||||
mod components;
|
||||
mod fetch;
|
||||
#[cfg(windows)]
|
||||
mod job;
|
||||
mod paths;
|
||||
mod service;
|
||||
mod store;
|
||||
mod units;
|
||||
#[cfg(windows)]
|
||||
mod winsvc;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::{Parser, Subcommand};
|
||||
use ps_ipc::transport::{Address, Server};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "proxy-suite-service", version, about = "Proxy Suite's service")]
|
||||
struct Args {
|
||||
/// Run in the foreground instead of under the Service Control Manager.
|
||||
#[arg(long)]
|
||||
console: bool,
|
||||
/// Where the configuration and state live (default: %ProgramData%\ProxySuite).
|
||||
#[arg(long, value_name = "DIR")]
|
||||
state_dir: Option<PathBuf>,
|
||||
/// The API's pipe or socket (default: \\.\pipe\proxy-suite, or $TMPDIR/proxy-suite.sock).
|
||||
#[arg(long, value_name = "ADDRESS")]
|
||||
socket: Option<String>,
|
||||
#[command(subcommand)]
|
||||
command: Option<Command>,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
/// Register the Windows service (started at boot, as LocalSystem).
|
||||
Install,
|
||||
/// Remove the Windows service.
|
||||
Uninstall,
|
||||
}
|
||||
|
||||
fn address(arg: Option<String>) -> Address {
|
||||
match arg {
|
||||
Some(s) if cfg!(windows) => Address::Pipe(s),
|
||||
Some(s) => Address::Unix(s.into()),
|
||||
None => Address::default_for_platform(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything the service does, until `shutdown` resolves.
|
||||
pub async fn run(state_dir: Option<PathBuf>, socket: Option<String>, shutdown: impl std::future::Future<Output = ()>) -> Result<()> {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
let paths = state_dir.map(paths::Paths::new).unwrap_or_else(paths::Paths::platform_default);
|
||||
let svc = service::Service::new(paths.clone()).with_context(|| format!("opening {}", paths.root.display()))?;
|
||||
let interactive = svc.cfg().user_control.enable;
|
||||
let shared = Arc::new(Mutex::new(svc));
|
||||
|
||||
let addr = address(socket);
|
||||
let server = Server::bind(&addr, interactive).with_context(|| format!("listening on {addr:?}"))?;
|
||||
tracing::info!("listening on {addr:?}, state in {}", paths.root.display());
|
||||
|
||||
if let Err(e) = shared.lock().await.apply().await {
|
||||
tracing::warn!("not starting the proxy yet: {e}");
|
||||
}
|
||||
tokio::spawn(api::serve(server, shared.clone()));
|
||||
// First fetches: what the configuration needs and has not got yet.
|
||||
{
|
||||
let shared = shared.clone();
|
||||
tokio::spawn(async move {
|
||||
let missing: Vec<String> = {
|
||||
let s = shared.lock().await;
|
||||
s.cfg().proxy.subscriptions.iter().filter(|x| !s.store.subscriptions.contains_key(&x.tag)).map(|x| x.tag.clone()).collect()
|
||||
};
|
||||
for tag in missing {
|
||||
service::update_subscriptions(&shared, Some(&tag)).await;
|
||||
}
|
||||
service::update_rule_sets(&shared, true).await;
|
||||
service::timers(shared).await;
|
||||
});
|
||||
}
|
||||
|
||||
shutdown.await;
|
||||
tracing::info!("stopping");
|
||||
shared.lock().await.sup.stop_all().await;
|
||||
if let Address::Unix(path) = addr {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()))
|
||||
.with_writer(std::io::stderr)
|
||||
.init();
|
||||
match args.command {
|
||||
#[cfg(windows)]
|
||||
Some(Command::Install) => return winsvc::install(),
|
||||
#[cfg(windows)]
|
||||
Some(Command::Uninstall) => return winsvc::uninstall(),
|
||||
#[cfg(not(windows))]
|
||||
Some(_) => anyhow::bail!("there are no services to install off Windows; use --console"),
|
||||
None => {}
|
||||
}
|
||||
if args.console || !cfg!(windows) {
|
||||
let rt = tokio::runtime::Runtime::new()?;
|
||||
return rt.block_on(run(args.state_dir, args.socket, async {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
}));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
winsvc::dispatch()
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
unreachable!()
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Where the service keeps everything.
|
||||
//!
|
||||
//! `%ProgramData%\ProxySuite` on Windows, or `--state-dir` (any platform, for development
|
||||
//! and tests):
|
||||
//!
|
||||
//! ```text
|
||||
//! config.json the configuration, written only by the service
|
||||
//! state.json pins, disabled outbounds, the route mode
|
||||
//! secrets.json what the service generated: the Clash API secret, the hop login
|
||||
//! subscriptions/ each subscription's links as fetched last
|
||||
//! rule-sets/ downloaded geodata and rule sets
|
||||
//! cache/ sing-box's fake IP cache
|
||||
//! run/ the rendered backend configs
|
||||
//! logs/ one log per unit
|
||||
//! bin/ the components (sing-box, xray, winws, …)
|
||||
//! ```
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Paths {
|
||||
pub root: PathBuf,
|
||||
}
|
||||
|
||||
impl Paths {
|
||||
pub fn new(root: impl Into<PathBuf>) -> Self {
|
||||
Self { root: root.into() }
|
||||
}
|
||||
|
||||
/// `%ProgramData%\ProxySuite`, or `/var/lib/proxy-suite-windows` elsewhere.
|
||||
pub fn platform_default() -> Self {
|
||||
if cfg!(windows) {
|
||||
let base = std::env::var_os("ProgramData").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(r"C:\ProgramData"));
|
||||
Self::new(base.join("ProxySuite"))
|
||||
} else {
|
||||
Self::new("/var/lib/proxy-suite-windows")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn config(&self) -> PathBuf {
|
||||
self.root.join("config.json")
|
||||
}
|
||||
pub fn state(&self) -> PathBuf {
|
||||
self.root.join("state.json")
|
||||
}
|
||||
pub fn secrets(&self) -> PathBuf {
|
||||
self.root.join("secrets.json")
|
||||
}
|
||||
pub fn subscriptions(&self) -> PathBuf {
|
||||
self.root.join("subscriptions")
|
||||
}
|
||||
pub fn rule_sets(&self) -> PathBuf {
|
||||
self.root.join("rule-sets")
|
||||
}
|
||||
pub fn cache(&self) -> PathBuf {
|
||||
self.root.join("cache")
|
||||
}
|
||||
pub fn run(&self) -> PathBuf {
|
||||
self.root.join("run")
|
||||
}
|
||||
pub fn logs(&self) -> PathBuf {
|
||||
self.root.join("logs")
|
||||
}
|
||||
pub fn bin(&self) -> PathBuf {
|
||||
self.root.join("bin")
|
||||
}
|
||||
|
||||
pub fn create_all(&self) -> std::io::Result<()> {
|
||||
for dir in [self.root.clone(), self.subscriptions(), self.rule_sets(), self.cache(), self.run(), self.logs(), self.bin()] {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `data` to `path` through a temporary file and a rename, so a reader never sees half
|
||||
/// of it and a crash leaves the old one.
|
||||
pub fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> {
|
||||
let tmp = path.with_extension("tmp");
|
||||
std::fs::write(&tmp, data)?;
|
||||
std::fs::rename(&tmp, path)
|
||||
}
|
||||
|
||||
/// Whether `path` holds exactly `data` already.
|
||||
pub fn same_content(path: &Path, data: &[u8]) -> bool {
|
||||
std::fs::read(path).is_ok_and(|old| old == data)
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
//! The service's state and what it does with it: render, write, check, (re)start, fetch.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use ps_core::config::{Backend, Config, RuleSetFormat};
|
||||
use ps_core::render::{self, Env, Input, Rendered};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::components::Components;
|
||||
use crate::fetch;
|
||||
use crate::paths::{Paths, same_content, write_atomic};
|
||||
use crate::store::{Store, random_uuid};
|
||||
use crate::units::{Supervisor, UnitSpec, UnitState};
|
||||
|
||||
pub const SOCKS_UNIT: &str = "proxy-suite-socks";
|
||||
pub const SIDECAR_UNIT: &str = "proxy-suite-xray-sidecar";
|
||||
|
||||
pub type Shared = Arc<Mutex<Service>>;
|
||||
|
||||
pub struct Service {
|
||||
pub store: Store,
|
||||
pub sup: Supervisor,
|
||||
pub comps: Components,
|
||||
/// `proxy-ctl proxy off` stops the local proxy until `on` or the next start.
|
||||
pub proxy_on: bool,
|
||||
/// The global TUN, on with `proxy.autostart = "tun"` or `proxy-ctl proxy tun on`.
|
||||
pub tun: bool,
|
||||
sidecar_secret: String,
|
||||
pub last: Option<Rendered>,
|
||||
/// Why the last apply did not take.
|
||||
pub last_error: Option<String>,
|
||||
pub last_fetch: BTreeMap<String, SystemTime>,
|
||||
}
|
||||
|
||||
fn digest(data: &[u8]) -> String {
|
||||
let mut h = Sha256::new();
|
||||
h.update(data);
|
||||
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
impl Service {
|
||||
pub fn new(paths: Paths) -> Result<Self> {
|
||||
let store = Store::open(paths.clone())?;
|
||||
let tun = store.config.proxy.autostart.is_some() && store.config.proxy.tun.enable;
|
||||
Ok(Self {
|
||||
sup: Supervisor::new(paths.logs()),
|
||||
comps: Components::new(paths.bin()),
|
||||
proxy_on: true,
|
||||
tun,
|
||||
sidecar_secret: random_uuid(),
|
||||
last: None,
|
||||
last_error: None,
|
||||
last_fetch: BTreeMap::new(),
|
||||
store,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn paths(&self) -> &Paths {
|
||||
&self.store.paths
|
||||
}
|
||||
|
||||
pub fn cfg(&self) -> &Config {
|
||||
&self.store.config
|
||||
}
|
||||
|
||||
fn proxy_wanted(&self) -> bool {
|
||||
let cfg = self.cfg();
|
||||
cfg.enable && cfg.proxy.enable && self.proxy_on
|
||||
}
|
||||
|
||||
fn env(&self) -> Env {
|
||||
let paths = self.paths();
|
||||
let cfg = self.cfg();
|
||||
let mut direct = Vec::new();
|
||||
if cfg.proxy.backend == Backend::Hybrid {
|
||||
if let Some(x) = self.comps.xray() {
|
||||
direct.push(x.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
Env {
|
||||
rule_sets: self.store.rule_set_files(),
|
||||
empty_rule_set: paths.run().join("empty-rule-set.json").to_string_lossy().into_owned(),
|
||||
cache_dir: paths.cache().to_string_lossy().into_owned(),
|
||||
clash_secret: Some(self.store.secrets.clash_secret.clone()),
|
||||
hop_login: Some((self.store.secrets.hop_user.clone(), self.store.secrets.hop_password.clone())),
|
||||
direct_processes: direct,
|
||||
groups_watched: false,
|
||||
sidecar_secret: self.sidecar_secret.clone(),
|
||||
windows: cfg!(windows),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders and returns the result, without touching anything.
|
||||
pub fn render(&self) -> Result<Rendered, render::RenderError> {
|
||||
let env = self.env();
|
||||
let read = |path: &str| std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"));
|
||||
render::render(&Input {
|
||||
cfg: self.cfg(),
|
||||
state: &self.store.state,
|
||||
subscriptions: &self.store.subscriptions,
|
||||
env: &env,
|
||||
read_file: &read,
|
||||
tun: self.tun && self.cfg().proxy.tun.enable,
|
||||
})
|
||||
}
|
||||
|
||||
/// Brings the units in line with the configuration: render, write, check, start or
|
||||
/// restart what changed, stop what is no longer wanted.
|
||||
pub async fn apply(&mut self) -> Result<()> {
|
||||
if !self.proxy_wanted() {
|
||||
self.sup.stop(SOCKS_UNIT).await;
|
||||
self.sup.stop(SIDECAR_UNIT).await;
|
||||
self.last_error = None;
|
||||
return Ok(());
|
||||
}
|
||||
let run = self.paths().run();
|
||||
let empty = run.join("empty-rule-set.json");
|
||||
if !empty.exists() {
|
||||
write_atomic(&empty, br#"{"version":1,"rules":[]}"#)?;
|
||||
}
|
||||
let rendered = match self.render() {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
self.last_error = Some(e.0.clone());
|
||||
self.sup.note(SOCKS_UNIT, format!("proxy-suite: not starting: {e}"));
|
||||
return Err(anyhow::anyhow!(e.0));
|
||||
}
|
||||
};
|
||||
for w in &rendered.warnings {
|
||||
self.sup.note(SOCKS_UNIT, format!("proxy-suite: warning: {w}"));
|
||||
}
|
||||
|
||||
let backend = self.cfg().proxy.backend;
|
||||
let main_program = match backend {
|
||||
Backend::Xray => self.comps.xray().context("xray is not installed")?,
|
||||
_ => self.comps.sing_box().context("sing-box is not installed (proxy-ctl components install)")?,
|
||||
};
|
||||
let main_json = serde_json::to_vec_pretty(rendered.sing_box.as_ref().or(rendered.xray.as_ref()).unwrap())?;
|
||||
let main_path = run.join(if backend == Backend::Xray { "xray.json" } else { "sing-box.json" });
|
||||
// Checked before it replaces the running one: a config the backend refuses keeps the
|
||||
// last good one running.
|
||||
let candidate = run.join("candidate.json");
|
||||
write_atomic(&candidate, &main_json)?;
|
||||
if backend != Backend::Xray {
|
||||
let out = tokio::process::Command::new(&main_program).args(["check", "-c"]).arg(&candidate).output().await?;
|
||||
if !out.status.success() {
|
||||
let why = String::from_utf8_lossy(&out.stderr).trim().to_owned();
|
||||
self.last_error = Some(format!("sing-box refused the rendered config: {why}"));
|
||||
self.sup.note(SOCKS_UNIT, format!("proxy-suite: sing-box refused the new config, keeping the old one: {why}"));
|
||||
anyhow::bail!("sing-box refused the rendered config: {why}");
|
||||
}
|
||||
}
|
||||
if !same_content(&main_path, &main_json) {
|
||||
std::fs::rename(&candidate, &main_path)?;
|
||||
}
|
||||
let mut args: Vec<String> = vec!["run".into(), "-c".into(), main_path.to_string_lossy().into_owned()];
|
||||
if backend != Backend::Xray {
|
||||
args.extend(["-D".into(), run.to_string_lossy().into_owned(), "--disable-color".into()]);
|
||||
}
|
||||
self.sup.ensure(UnitSpec {
|
||||
name: SOCKS_UNIT.into(),
|
||||
program: main_program,
|
||||
args,
|
||||
env: Vec::new(),
|
||||
cwd: Some(run.clone()),
|
||||
generation: digest(&main_json),
|
||||
});
|
||||
|
||||
match (backend, &rendered.xray) {
|
||||
(Backend::Hybrid, Some(sidecar)) => {
|
||||
let xray = self.comps.xray().context("xray is not installed; the hybrid backend needs it")?;
|
||||
let json = serde_json::to_vec_pretty(sidecar)?;
|
||||
let path = run.join("xray-sidecar.json");
|
||||
if !same_content(&path, &json) {
|
||||
write_atomic(&path, &json)?;
|
||||
}
|
||||
self.sup.ensure(UnitSpec {
|
||||
name: SIDECAR_UNIT.into(),
|
||||
program: xray,
|
||||
args: vec!["run".into(), "-c".into(), path.to_string_lossy().into_owned()],
|
||||
env: Vec::new(),
|
||||
cwd: Some(run.clone()),
|
||||
generation: digest(&json),
|
||||
});
|
||||
}
|
||||
_ => self.sup.stop(SIDECAR_UNIT).await,
|
||||
}
|
||||
self.last = Some(rendered);
|
||||
self.last_error = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The routes a fetch tries: the local proxy if it runs, and (with directFallbacks or
|
||||
/// without it) directly.
|
||||
pub fn fetch_routes(&self, via_proxy: bool) -> Vec<fetch::Route> {
|
||||
let cfg = self.cfg();
|
||||
let mut routes = Vec::new();
|
||||
if via_proxy && self.sup.state_of(SOCKS_UNIT) == UnitState::Active {
|
||||
let auth = &cfg.proxy.listener.auth;
|
||||
let login = auth.username.clone().zip(auth.password.clone());
|
||||
routes.push(fetch::Route::Proxy { port: cfg.proxy.listener.port, login });
|
||||
if !cfg.kill_switch.enable || cfg.kill_switch.direct_fallbacks {
|
||||
routes.push(fetch::Route::Direct);
|
||||
}
|
||||
} else {
|
||||
routes.push(fetch::Route::Direct);
|
||||
}
|
||||
routes
|
||||
}
|
||||
|
||||
pub fn status(&self) -> Value {
|
||||
let cfg = self.cfg();
|
||||
let units: Vec<Value> = self.sup.status().into_iter().map(|u| serde_json::to_value(u).unwrap()).collect();
|
||||
let socks = self.sup.state_of(SOCKS_UNIT);
|
||||
json!({
|
||||
"units": units,
|
||||
"proxy": {
|
||||
"enabled": cfg.proxy.enable,
|
||||
"on": self.proxy_wanted(),
|
||||
"state": socks.as_str(),
|
||||
"backend": cfg.proxy.backend.as_str(),
|
||||
"listener": format!("{}:{}", cfg.proxy.listener.address, cfg.proxy.listener.port),
|
||||
"tun": self.tun && cfg.proxy.tun.enable,
|
||||
"mode": self.store.state.route_mode.map(|m| m.as_str()),
|
||||
"pinned": self.store.state.pin,
|
||||
"selection": cfg.proxy.selection.as_str(),
|
||||
},
|
||||
"warnings": self.last.as_ref().map(|r| r.warnings.clone()).unwrap_or_default(),
|
||||
"error": self.last_error,
|
||||
"revision": self.store.revision,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches the subscriptions (all, or `only`), saves what came, and applies.
|
||||
pub async fn update_subscriptions(shared: &Shared, only: Option<&str>) -> Vec<(String, Result<usize, String>)> {
|
||||
let jobs: Vec<(String, Result<String, String>, Vec<fetch::Route>)> = {
|
||||
let s = shared.lock().await;
|
||||
s.cfg()
|
||||
.proxy
|
||||
.subscriptions
|
||||
.iter()
|
||||
.filter(|sub| only.is_none_or(|t| t == sub.tag))
|
||||
.map(|sub| {
|
||||
let url = match (&sub.url, &sub.url_file) {
|
||||
(Some(u), _) => Ok(u.trim().to_owned()),
|
||||
(None, Some(f)) => std::fs::read_to_string(f).map(|s| s.trim().to_owned()).map_err(|e| format!("{f}: {e}")),
|
||||
(None, None) => Err("no url or urlFile".into()),
|
||||
};
|
||||
(sub.tag.clone(), url, s.fetch_routes(true))
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let mut results = Vec::new();
|
||||
for (tag, url, routes) in jobs {
|
||||
let result = match url {
|
||||
Err(e) => Err(e),
|
||||
Ok(url) => fetch::subscription(&url, &routes).await.map_err(|e| e.to_string()),
|
||||
};
|
||||
let mut s = shared.lock().await;
|
||||
match result {
|
||||
Ok(lines) => {
|
||||
let n = lines.len();
|
||||
if let Err(e) = s.store.save_subscription(&tag, lines) {
|
||||
results.push((tag, Err(e.to_string())));
|
||||
continue;
|
||||
}
|
||||
s.last_fetch.insert(format!("sub:{tag}"), SystemTime::now());
|
||||
s.sup.note(SOCKS_UNIT, format!("proxy-suite: subscription '{tag}': {n} links"));
|
||||
results.push((tag, Ok(n)));
|
||||
}
|
||||
Err(e) => {
|
||||
s.last_fetch.insert(format!("sub:{tag}"), SystemTime::now());
|
||||
s.sup.note(SOCKS_UNIT, format!("proxy-suite: subscription '{tag}' could not be fetched: {e}"));
|
||||
results.push((tag, Err(e)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut s = shared.lock().await;
|
||||
let _ = s.apply().await;
|
||||
results
|
||||
}
|
||||
|
||||
/// Fetches the rule sets and geodata the configuration wants (all, or those missing), and
|
||||
/// applies when something new came.
|
||||
pub async fn update_rule_sets(shared: &Shared, missing_only: bool) -> Vec<(String, Result<(), String>)> {
|
||||
let (wanted, have, dir, sing_box, routes_proxy, routes_direct) = {
|
||||
let s = shared.lock().await;
|
||||
(
|
||||
render::wanted_rule_sets(s.cfg()),
|
||||
s.store.rule_set_files(),
|
||||
s.paths().rule_sets(),
|
||||
s.comps.sing_box(),
|
||||
s.fetch_routes(true),
|
||||
s.fetch_routes(false),
|
||||
)
|
||||
};
|
||||
let mut results = Vec::new();
|
||||
let mut changed = false;
|
||||
for w in wanted.iter().filter(|w| w.dns_copy_of.is_none()) {
|
||||
if missing_only && have.contains_key(&w.tag) {
|
||||
continue;
|
||||
}
|
||||
let ext = if w.format == RuleSetFormat::Binary { "srs" } else { "json" };
|
||||
let dest = dir.join(format!("{}.{ext}", w.tag));
|
||||
let routes = if w.via_proxy { &routes_proxy } else { &routes_direct };
|
||||
let r = fetch::rule_set(&w.url, routes, &dest).await.map_err(|e| e.to_string());
|
||||
changed |= r.is_ok();
|
||||
results.push((w.tag.clone(), r));
|
||||
}
|
||||
// The DNS copies, from what was fetched.
|
||||
for w in wanted.iter().filter(|w| w.dns_copy_of.is_some()) {
|
||||
let of = w.dns_copy_of.as_deref().unwrap();
|
||||
let src_json = dir.join(format!("{of}.json"));
|
||||
let src_srs = dir.join(format!("{of}.srs"));
|
||||
let dest = dir.join(format!("{}.json", w.tag));
|
||||
if missing_only && dest.exists() && !changed {
|
||||
continue;
|
||||
}
|
||||
let source: Result<Value> = if src_json.exists() {
|
||||
std::fs::read_to_string(&src_json).map_err(Into::into).and_then(|t| serde_json::from_str(&t).map_err(Into::into))
|
||||
} else if let (true, Some(sb)) = (src_srs.exists(), &sing_box) {
|
||||
decompile(sb, &src_srs).await
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let r = source
|
||||
.and_then(|src| Ok(write_atomic(&dest, serde_json::to_string(&fetch::domain_only(&src))?.as_bytes())?))
|
||||
.map_err(|e| e.to_string());
|
||||
results.push((w.tag.clone(), r));
|
||||
}
|
||||
if changed {
|
||||
let mut s = shared.lock().await;
|
||||
let _ = s.apply().await;
|
||||
}
|
||||
results
|
||||
}
|
||||
|
||||
async fn decompile(sing_box: &PathBuf, srs: &std::path::Path) -> Result<Value> {
|
||||
let out = srs.with_extension("decompiled.json");
|
||||
let status = tokio::process::Command::new(sing_box)
|
||||
.args(["rule-set", "decompile", "--output"])
|
||||
.arg(&out)
|
||||
.arg(srs)
|
||||
.status()
|
||||
.await?;
|
||||
anyhow::ensure!(status.success(), "sing-box could not decompile {}", srs.display());
|
||||
let v = serde_json::from_str(&std::fs::read_to_string(&out)?)?;
|
||||
let _ = std::fs::remove_file(&out);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The timers: subscriptions and rule sets, each on its interval.
|
||||
pub async fn timers(shared: Shared) {
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_secs(60)).await;
|
||||
let (sub_due, rules_due) = {
|
||||
let s = shared.lock().await;
|
||||
let cfg = s.cfg();
|
||||
let every = |text: &str, default: u64| ps_core::duration::parse(text).unwrap_or(Duration::from_secs(default));
|
||||
let sub_every = every(&cfg.proxy.subscription_update_interval, 86400);
|
||||
let rules_every = every(&cfg.proxy.routing.rule_set_update_interval, 86400);
|
||||
let due = |key: &str, every: Duration| {
|
||||
s.last_fetch.get(key).is_none_or(|t| t.elapsed().unwrap_or_default() >= every)
|
||||
};
|
||||
let subs: Vec<String> =
|
||||
cfg.proxy.subscriptions.iter().filter(|x| due(&format!("sub:{}", x.tag), sub_every)).map(|x| x.tag.clone()).collect();
|
||||
(subs, due("rule-sets", rules_every))
|
||||
};
|
||||
for tag in sub_due {
|
||||
update_subscriptions(&shared, Some(&tag)).await;
|
||||
}
|
||||
if rules_due {
|
||||
shared.lock().await.last_fetch.insert("rule-sets".into(), SystemTime::now());
|
||||
update_rule_sets(&shared, false).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
//! The configuration, runtime state and generated secrets, as files.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use ps_core::config::Config;
|
||||
use ps_core::render::{RuleSetFile, State};
|
||||
use rand::Rng;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::paths::{Paths, write_atomic};
|
||||
|
||||
/// What the service generated once and keeps.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Secrets {
|
||||
pub clash_secret: String,
|
||||
pub hop_user: String,
|
||||
pub hop_password: String,
|
||||
}
|
||||
|
||||
pub fn random_token(len: usize) -> String {
|
||||
const CHARS: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
let mut rng = rand::rng();
|
||||
(0..len).map(|_| CHARS[rng.random_range(0..CHARS.len())] as char).collect()
|
||||
}
|
||||
|
||||
pub fn random_uuid() -> String {
|
||||
let mut rng = rand::rng();
|
||||
let b: [u8; 16] = rng.random();
|
||||
format!(
|
||||
"{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}",
|
||||
u32::from_be_bytes([b[0], b[1], b[2], b[3]]),
|
||||
u16::from_be_bytes([b[4], b[5]]),
|
||||
u16::from_be_bytes([b[6], b[7]]) & 0x0fff,
|
||||
(u16::from_be_bytes([b[8], b[9]]) & 0x3fff) | 0x8000,
|
||||
u64::from_be_bytes([0, 0, b[10], b[11], b[12], b[13], b[14], b[15]])
|
||||
)
|
||||
}
|
||||
|
||||
pub struct Store {
|
||||
pub paths: Paths,
|
||||
pub config: Config,
|
||||
/// Bumped by every change of `config`: a client edits against a revision.
|
||||
pub revision: u64,
|
||||
pub state: State,
|
||||
pub secrets: Secrets,
|
||||
/// Each subscription's links as fetched last.
|
||||
pub subscriptions: BTreeMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub fn open(paths: Paths) -> Result<Self> {
|
||||
paths.create_all().with_context(|| format!("creating {}", paths.root.display()))?;
|
||||
let config = match std::fs::read_to_string(paths.config()) {
|
||||
Ok(text) => Config::from_json(&text).with_context(|| format!("reading {}", paths.config().display()))?,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Config::default(),
|
||||
Err(e) => return Err(e).with_context(|| format!("reading {}", paths.config().display())),
|
||||
};
|
||||
let state = std::fs::read_to_string(paths.state())
|
||||
.ok()
|
||||
.and_then(|t| serde_json::from_str(&t).ok())
|
||||
.unwrap_or_default();
|
||||
let secrets = match std::fs::read_to_string(paths.secrets()).ok().and_then(|t| serde_json::from_str(&t).ok()) {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
let s = Secrets { clash_secret: random_token(32), hop_user: "hop".into(), hop_password: random_token(32) };
|
||||
write_atomic(&paths.secrets(), serde_json::to_string_pretty(&s)?.as_bytes())?;
|
||||
s
|
||||
}
|
||||
};
|
||||
let mut store = Self { paths, config, revision: 1, state, secrets, subscriptions: BTreeMap::new() };
|
||||
store.load_subscriptions();
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
pub fn save_config(&mut self, config: Config) -> Result<()> {
|
||||
write_atomic(&self.paths.config(), config.to_json_pretty().as_bytes())?;
|
||||
self.config = config;
|
||||
self.revision += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn save_state(&self) -> Result<()> {
|
||||
write_atomic(&self.paths.state(), serde_json::to_string_pretty(&self.state)?.as_bytes())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sub_path(&self, tag: &str) -> std::path::PathBuf {
|
||||
self.paths.subscriptions().join(format!("{tag}.txt"))
|
||||
}
|
||||
|
||||
fn load_subscriptions(&mut self) {
|
||||
for sub in &self.config.proxy.subscriptions {
|
||||
if let Ok(text) = std::fs::read_to_string(self.sub_path(&sub.tag)) {
|
||||
self.subscriptions.insert(sub.tag.clone(), text.lines().map(str::to_owned).collect());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save_subscription(&mut self, tag: &str, lines: Vec<String>) -> Result<()> {
|
||||
write_atomic(&self.sub_path(tag), lines.join("\n").as_bytes())?;
|
||||
self.subscriptions.insert(tag.to_owned(), lines);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The downloaded rule sets, by tag.
|
||||
pub fn rule_set_files(&self) -> BTreeMap<String, RuleSetFile> {
|
||||
let mut out = BTreeMap::new();
|
||||
let Ok(dir) = std::fs::read_dir(self.paths.rule_sets()) else { return out };
|
||||
for entry in dir.flatten() {
|
||||
let path = entry.path();
|
||||
let (Some(stem), Some(ext)) = (path.file_stem().and_then(|s| s.to_str()), path.extension().and_then(|s| s.to_str())) else {
|
||||
continue;
|
||||
};
|
||||
let format = match ext {
|
||||
"srs" => ps_core::config::RuleSetFormat::Binary,
|
||||
"json" => ps_core::config::RuleSetFormat::Source,
|
||||
_ => continue,
|
||||
};
|
||||
out.insert(stem.to_owned(), RuleSetFile { path: path.to_string_lossy().into_owned(), format });
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
//! The supervisor: what systemd does for upstream. Each unit is one program, started,
|
||||
//! watched, restarted with backoff when it dies, its output kept in a ring and a log file.
|
||||
//! On Windows every child joins a Job Object that kills it with the service.
|
||||
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Stdio;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use serde::Serialize;
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
use tokio::process::Command;
|
||||
use tokio::sync::{broadcast, watch};
|
||||
|
||||
/// How to run a unit. Two specs that compare equal need no restart.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UnitSpec {
|
||||
pub name: String,
|
||||
pub program: PathBuf,
|
||||
pub args: Vec<String>,
|
||||
pub env: Vec<(String, String)>,
|
||||
pub cwd: Option<PathBuf>,
|
||||
/// Changes when a file the unit reads changes (its rendered config): a restart.
|
||||
pub generation: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum UnitState {
|
||||
Inactive,
|
||||
Activating,
|
||||
Active,
|
||||
Deactivating,
|
||||
Failed,
|
||||
}
|
||||
|
||||
impl UnitState {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Inactive => "inactive",
|
||||
Self::Activating => "activating",
|
||||
Self::Active => "active",
|
||||
Self::Deactivating => "deactivating",
|
||||
Self::Failed => "failed",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct LogLine {
|
||||
pub unit: String,
|
||||
/// Unix time, milliseconds.
|
||||
pub at: u64,
|
||||
pub line: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct UnitStatus {
|
||||
pub name: String,
|
||||
pub state: UnitState,
|
||||
pub pid: Option<u32>,
|
||||
pub restarts: u32,
|
||||
/// Why it failed last.
|
||||
pub result: Option<String>,
|
||||
pub since: Option<u64>,
|
||||
}
|
||||
|
||||
const RING: usize = 2000;
|
||||
/// A unit that fails this many times within `START_LIMIT_INTERVAL` stays failed.
|
||||
const START_LIMIT: usize = 5;
|
||||
const START_LIMIT_INTERVAL: Duration = Duration::from_secs(60);
|
||||
/// A unit whose log file outgrows this starts a new one, keeping one old.
|
||||
const LOG_FILE_MAX: u64 = 5 * 1024 * 1024;
|
||||
|
||||
struct Shared {
|
||||
state: UnitState,
|
||||
pid: Option<u32>,
|
||||
restarts: u32,
|
||||
result: Option<String>,
|
||||
since: Option<u64>,
|
||||
}
|
||||
|
||||
struct Unit {
|
||||
spec: UnitSpec,
|
||||
shared: Arc<Mutex<Shared>>,
|
||||
stop: watch::Sender<bool>,
|
||||
task: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
|
||||
pub struct Supervisor {
|
||||
units: BTreeMap<String, Unit>,
|
||||
logs: Arc<Mutex<BTreeMap<String, VecDeque<LogLine>>>>,
|
||||
log_dir: PathBuf,
|
||||
feed: broadcast::Sender<LogLine>,
|
||||
#[cfg(windows)]
|
||||
job: Option<crate::job::Job>,
|
||||
}
|
||||
|
||||
fn now_ms() -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64)
|
||||
}
|
||||
|
||||
impl Supervisor {
|
||||
pub fn new(log_dir: PathBuf) -> Self {
|
||||
let (feed, _) = broadcast::channel(1024);
|
||||
Self {
|
||||
units: BTreeMap::new(),
|
||||
logs: Arc::new(Mutex::new(BTreeMap::new())),
|
||||
log_dir,
|
||||
feed,
|
||||
#[cfg(windows)]
|
||||
job: crate::job::Job::new().map_err(|e| tracing::warn!("no job object: {e}")).ok(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn subscribe(&self) -> broadcast::Receiver<LogLine> {
|
||||
self.feed.subscribe()
|
||||
}
|
||||
|
||||
/// The last `n` log lines of `unit`, or of every unit by time.
|
||||
pub fn tail(&self, unit: Option<&str>, n: usize) -> Vec<LogLine> {
|
||||
let logs = self.logs.lock().unwrap();
|
||||
let mut lines: Vec<LogLine> = match unit {
|
||||
Some(u) => logs.get(u).map(|r| r.iter().cloned().collect()).unwrap_or_default(),
|
||||
None => logs.values().flatten().cloned().collect(),
|
||||
};
|
||||
lines.sort_by_key(|l| l.at);
|
||||
let skip = lines.len().saturating_sub(n);
|
||||
lines.split_off(skip)
|
||||
}
|
||||
|
||||
/// A line of the service's own about a unit, in that unit's log.
|
||||
pub fn note(&self, unit: &str, line: impl Into<String>) {
|
||||
push_log(&self.logs, &self.feed, &self.log_dir, unit, line.into());
|
||||
}
|
||||
|
||||
pub fn status(&self) -> Vec<UnitStatus> {
|
||||
self.units
|
||||
.iter()
|
||||
.map(|(name, u)| {
|
||||
let s = u.shared.lock().unwrap();
|
||||
UnitStatus { name: name.clone(), state: s.state, pid: s.pid, restarts: s.restarts, result: s.result.clone(), since: s.since }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn state_of(&self, name: &str) -> UnitState {
|
||||
self.units.get(name).map_or(UnitState::Inactive, |u| u.shared.lock().unwrap().state)
|
||||
}
|
||||
|
||||
/// Runs `spec`, restarting the unit if it runs another spec, leaving it be if it runs this one.
|
||||
pub fn ensure(&mut self, spec: UnitSpec) {
|
||||
if let Some(u) = self.units.get(&spec.name) {
|
||||
let alive = !u.task.is_finished();
|
||||
if alive && u.spec == spec && u.shared.lock().unwrap().state != UnitState::Failed {
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.start(spec);
|
||||
}
|
||||
|
||||
/// Starts `spec`, stopping what ran under its name first.
|
||||
pub fn start(&mut self, spec: UnitSpec) {
|
||||
let name = spec.name.clone();
|
||||
self.stop_now(&name);
|
||||
let shared = Arc::new(Mutex::new(Shared { state: UnitState::Activating, pid: None, restarts: 0, result: None, since: Some(now_ms()) }));
|
||||
let (stop_tx, stop_rx) = watch::channel(false);
|
||||
let ctx = RunCtx {
|
||||
spec: spec.clone(),
|
||||
shared: shared.clone(),
|
||||
logs: self.logs.clone(),
|
||||
feed: self.feed.clone(),
|
||||
log_dir: self.log_dir.clone(),
|
||||
#[cfg(windows)]
|
||||
job: self.job.as_ref().map(|j| j.handle()),
|
||||
};
|
||||
let task = tokio::spawn(run(ctx, stop_rx));
|
||||
self.units.insert(name, Unit { spec, shared, stop: stop_tx, task });
|
||||
}
|
||||
|
||||
/// Restarts a unit with the spec it has.
|
||||
pub fn restart(&mut self, name: &str) -> bool {
|
||||
match self.units.get(name).map(|u| u.spec.clone()) {
|
||||
Some(spec) => {
|
||||
self.start(spec);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn stop_now(&mut self, name: &str) {
|
||||
if let Some(u) = self.units.remove(name) {
|
||||
let _ = u.stop.send(true);
|
||||
// The task kills the child as it sees the flag; it is not waited for here, but
|
||||
// the next start of the unit waits for nothing either: a listener still held for a
|
||||
// moment shows as one restart.
|
||||
let shared = u.shared.clone();
|
||||
tokio::spawn(async move {
|
||||
let _ = tokio::time::timeout(Duration::from_secs(10), u.task).await;
|
||||
shared.lock().unwrap().state = UnitState::Inactive;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops a unit and waits for its process to be gone.
|
||||
pub async fn stop(&mut self, name: &str) {
|
||||
if let Some(u) = self.units.remove(name) {
|
||||
let _ = u.stop.send(true);
|
||||
let _ = tokio::time::timeout(Duration::from_secs(10), u.task).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn names(&self) -> Vec<String> {
|
||||
self.units.keys().cloned().collect()
|
||||
}
|
||||
|
||||
pub async fn stop_all(&mut self) {
|
||||
for name in self.names() {
|
||||
self.stop(&name).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct RunCtx {
|
||||
spec: UnitSpec,
|
||||
shared: Arc<Mutex<Shared>>,
|
||||
logs: Arc<Mutex<BTreeMap<String, VecDeque<LogLine>>>>,
|
||||
feed: broadcast::Sender<LogLine>,
|
||||
log_dir: PathBuf,
|
||||
#[cfg(windows)]
|
||||
job: Option<isize>,
|
||||
}
|
||||
|
||||
fn push_log(
|
||||
logs: &Arc<Mutex<BTreeMap<String, VecDeque<LogLine>>>>,
|
||||
feed: &broadcast::Sender<LogLine>,
|
||||
log_dir: &std::path::Path,
|
||||
unit: &str,
|
||||
line: String,
|
||||
) {
|
||||
let entry = LogLine { unit: unit.to_owned(), at: now_ms(), line };
|
||||
{
|
||||
let mut logs = logs.lock().unwrap();
|
||||
let ring = logs.entry(unit.to_owned()).or_default();
|
||||
if ring.len() >= RING {
|
||||
ring.pop_front();
|
||||
}
|
||||
ring.push_back(entry.clone());
|
||||
}
|
||||
let path = log_dir.join(format!("{unit}.log"));
|
||||
if std::fs::metadata(&path).is_ok_and(|m| m.len() > LOG_FILE_MAX) {
|
||||
let _ = std::fs::rename(&path, log_dir.join(format!("{unit}.log.1")));
|
||||
}
|
||||
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&path) {
|
||||
let _ = writeln!(f, "{} {}", entry.at, entry.line);
|
||||
}
|
||||
let _ = feed.send(entry);
|
||||
}
|
||||
|
||||
async fn run(ctx: RunCtx, mut stop: watch::Receiver<bool>) {
|
||||
let mut failures: VecDeque<Instant> = VecDeque::new();
|
||||
let mut backoff = Duration::from_millis(500);
|
||||
let log = |line: String| push_log(&ctx.logs, &ctx.feed, &ctx.log_dir, &ctx.spec.name, line);
|
||||
loop {
|
||||
let mut cmd = Command::new(&ctx.spec.program);
|
||||
cmd.args(&ctx.spec.args)
|
||||
.envs(ctx.spec.env.iter().map(|(k, v)| (k, v)))
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
if let Some(cwd) = &ctx.spec.cwd {
|
||||
cmd.current_dir(cwd);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
// No console window for the children.
|
||||
cmd.creation_flags(0x0800_0000);
|
||||
}
|
||||
let mut child = match cmd.spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
let why = format!("cannot start {}: {e}", ctx.spec.program.display());
|
||||
log(format!("proxy-suite: {why}"));
|
||||
let mut s = ctx.shared.lock().unwrap();
|
||||
s.state = UnitState::Failed;
|
||||
s.result = Some(why);
|
||||
return;
|
||||
}
|
||||
};
|
||||
#[cfg(windows)]
|
||||
if let (Some(job), Some(handle)) = (ctx.job, child.raw_handle()) {
|
||||
crate::job::assign(job, handle as isize);
|
||||
}
|
||||
{
|
||||
let mut s = ctx.shared.lock().unwrap();
|
||||
s.pid = child.id();
|
||||
s.state = UnitState::Activating;
|
||||
s.since = Some(now_ms());
|
||||
}
|
||||
log(format!("proxy-suite: started {} (pid {})", ctx.spec.program.display(), child.id().unwrap_or(0)));
|
||||
for pipe in [child.stdout.take().map(|p| Box::new(p) as Box<dyn tokio::io::AsyncRead + Send + Unpin>), child.stderr.take().map(|p| Box::new(p) as _)].into_iter().flatten() {
|
||||
let logs = ctx.logs.clone();
|
||||
let feed = ctx.feed.clone();
|
||||
let dir = ctx.log_dir.clone();
|
||||
let unit = ctx.spec.name.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut lines = BufReader::new(pipe).lines();
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
push_log(&logs, &feed, &dir, &unit, line);
|
||||
}
|
||||
});
|
||||
}
|
||||
// Up once it has lived a moment: none of the backends tells when it is ready.
|
||||
let started = Instant::now();
|
||||
let status = loop {
|
||||
tokio::select! {
|
||||
status = child.wait() => break Some(status),
|
||||
_ = tokio::time::sleep(Duration::from_millis(700)), if ctx.shared.lock().unwrap().state == UnitState::Activating => {
|
||||
ctx.shared.lock().unwrap().state = UnitState::Active;
|
||||
}
|
||||
_ = stop.changed() => {
|
||||
if *stop.borrow() {
|
||||
ctx.shared.lock().unwrap().state = UnitState::Deactivating;
|
||||
let _ = child.start_kill();
|
||||
let _ = tokio::time::timeout(Duration::from_secs(5), child.wait()).await;
|
||||
let mut s = ctx.shared.lock().unwrap();
|
||||
s.state = UnitState::Inactive;
|
||||
s.pid = None;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let why = match status {
|
||||
Some(Ok(s)) => format!("exited ({s})"),
|
||||
Some(Err(e)) => format!("lost ({e})"),
|
||||
None => "stopped".into(),
|
||||
};
|
||||
log(format!("proxy-suite: {} {why}", ctx.spec.name));
|
||||
let now = Instant::now();
|
||||
failures.push_back(now);
|
||||
while failures.front().is_some_and(|t| now - *t > START_LIMIT_INTERVAL) {
|
||||
failures.pop_front();
|
||||
}
|
||||
{
|
||||
let mut s = ctx.shared.lock().unwrap();
|
||||
s.pid = None;
|
||||
s.result = Some(why.clone());
|
||||
if failures.len() >= START_LIMIT {
|
||||
s.state = UnitState::Failed;
|
||||
drop(s);
|
||||
log(format!("proxy-suite: {} failed {START_LIMIT} times in a minute; not restarting it", ctx.spec.name));
|
||||
return;
|
||||
}
|
||||
s.state = UnitState::Activating;
|
||||
s.restarts += 1;
|
||||
}
|
||||
// A run that lasted a while starts the backoff over.
|
||||
if started.elapsed() > Duration::from_secs(30) {
|
||||
backoff = Duration::from_millis(500);
|
||||
}
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(backoff) => {}
|
||||
_ = stop.changed() => {
|
||||
if *stop.borrow() {
|
||||
ctx.shared.lock().unwrap().state = UnitState::Inactive;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
backoff = (backoff * 2).min(Duration::from_secs(30));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn spec(name: &str, program: &str, args: &[&str]) -> UnitSpec {
|
||||
UnitSpec {
|
||||
name: name.into(),
|
||||
program: program.into(),
|
||||
args: args.iter().map(|s| s.to_string()).collect(),
|
||||
env: Vec::new(),
|
||||
cwd: None,
|
||||
generation: "1".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_unit_runs_logs_and_stops() {
|
||||
let dir = std::env::temp_dir().join(format!("ps-units-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut sup = Supervisor::new(dir.clone());
|
||||
sup.start(spec("echo", "sh", &["-c", "echo hello; sleep 30"]));
|
||||
tokio::time::sleep(Duration::from_millis(1200)).await;
|
||||
assert_eq!(sup.state_of("echo"), UnitState::Active);
|
||||
assert!(sup.tail(Some("echo"), 10).iter().any(|l| l.line == "hello"));
|
||||
sup.stop("echo").await;
|
||||
assert_eq!(sup.state_of("echo"), UnitState::Inactive);
|
||||
assert!(std::fs::read_to_string(dir.join("echo.log")).unwrap().contains("hello"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_dying_unit_is_restarted_then_given_up_on() {
|
||||
let dir = std::env::temp_dir().join(format!("ps-units-die-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut sup = Supervisor::new(dir);
|
||||
sup.start(spec("dies", "sh", &["-c", "exit 3"]));
|
||||
tokio::time::sleep(Duration::from_secs(10)).await;
|
||||
let st = sup.status();
|
||||
assert_eq!(st[0].state, UnitState::Failed);
|
||||
assert!(st[0].restarts >= 3, "{st:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_missing_program_fails_at_once() {
|
||||
let mut sup = Supervisor::new(std::env::temp_dir());
|
||||
sup.start(spec("missing", "/nonexistent/program", &[]));
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(sup.state_of("missing"), UnitState::Failed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
//! The Windows service: registration, and the Service Control Manager's entry point.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use windows_service::service::{
|
||||
ServiceAccess, ServiceAction, ServiceActionType, ServiceControl, ServiceControlAccept, ServiceErrorControl,
|
||||
ServiceExitCode, ServiceFailureActions, ServiceFailureResetPeriod, ServiceInfo, ServiceStartType, ServiceState,
|
||||
ServiceStatus, ServiceType,
|
||||
};
|
||||
use windows_service::service_control_handler::{self, ServiceControlHandlerResult};
|
||||
use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};
|
||||
use windows_service::{define_windows_service, service_dispatcher};
|
||||
|
||||
pub const NAME: &str = "ProxySuite";
|
||||
const DISPLAY: &str = "Proxy Suite";
|
||||
const DESCRIPTION: &str = "Runs Proxy Suite's proxy, tunnels and DPI bypass, and serves the app's settings.";
|
||||
|
||||
pub fn install() -> Result<()> {
|
||||
let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE)
|
||||
.context("opening the Service Control Manager (run as an administrator)")?;
|
||||
let info = ServiceInfo {
|
||||
name: OsString::from(NAME),
|
||||
display_name: OsString::from(DISPLAY),
|
||||
service_type: ServiceType::OWN_PROCESS,
|
||||
start_type: ServiceStartType::AutoStart,
|
||||
error_control: ServiceErrorControl::Normal,
|
||||
executable_path: std::env::current_exe()?,
|
||||
launch_arguments: vec![],
|
||||
dependencies: vec![],
|
||||
account_name: None, // LocalSystem
|
||||
account_password: None,
|
||||
};
|
||||
let service = manager
|
||||
.create_service(&info, ServiceAccess::CHANGE_CONFIG | ServiceAccess::START)
|
||||
.context("creating the service")?;
|
||||
service.set_description(DESCRIPTION)?;
|
||||
// Restarted when it dies, as systemd's Restart=always.
|
||||
service.update_failure_actions(ServiceFailureActions {
|
||||
reset_period: ServiceFailureResetPeriod::After(Duration::from_secs(86400)),
|
||||
reboot_msg: None,
|
||||
command: None,
|
||||
actions: Some(vec![
|
||||
ServiceAction { action_type: ServiceActionType::Restart, delay: Duration::from_secs(2) },
|
||||
ServiceAction { action_type: ServiceActionType::Restart, delay: Duration::from_secs(10) },
|
||||
ServiceAction { action_type: ServiceActionType::Restart, delay: Duration::from_secs(60) },
|
||||
]),
|
||||
})?;
|
||||
service.start::<&str>(&[]).context("starting the service")?;
|
||||
println!("{DISPLAY} is installed and started.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn uninstall() -> Result<()> {
|
||||
let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)
|
||||
.context("opening the Service Control Manager (run as an administrator)")?;
|
||||
let service = manager
|
||||
.open_service(NAME, ServiceAccess::QUERY_STATUS | ServiceAccess::STOP | ServiceAccess::DELETE)
|
||||
.context("opening the service")?;
|
||||
if service.query_status()?.current_state != ServiceState::Stopped {
|
||||
let _ = service.stop();
|
||||
for _ in 0..30 {
|
||||
if service.query_status()?.current_state == ServiceState::Stopped {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
}
|
||||
}
|
||||
service.delete()?;
|
||||
println!("{DISPLAY} is removed.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
define_windows_service!(ffi_service_main, service_main);
|
||||
|
||||
pub fn dispatch() -> Result<()> {
|
||||
service_dispatcher::start(NAME, ffi_service_main).context("not started by the Service Control Manager; use --console to run in a terminal")
|
||||
}
|
||||
|
||||
fn service_main(_args: Vec<OsString>) {
|
||||
if let Err(e) = run_service() {
|
||||
tracing::error!("the service failed: {e:#}");
|
||||
}
|
||||
}
|
||||
|
||||
fn run_service() -> Result<()> {
|
||||
let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>();
|
||||
let mut stop_tx = Some(stop_tx);
|
||||
let handler = move |control| match control {
|
||||
ServiceControl::Stop | ServiceControl::Shutdown => {
|
||||
if let Some(tx) = stop_tx.take() {
|
||||
let _ = tx.send(());
|
||||
}
|
||||
ServiceControlHandlerResult::NoError
|
||||
}
|
||||
ServiceControl::Interrogate => ServiceControlHandlerResult::NoError,
|
||||
_ => ServiceControlHandlerResult::NotImplemented,
|
||||
};
|
||||
let status = service_control_handler::register(NAME, handler)?;
|
||||
let set = |state: ServiceState, accept: ServiceControlAccept| {
|
||||
status.set_service_status(ServiceStatus {
|
||||
service_type: ServiceType::OWN_PROCESS,
|
||||
current_state: state,
|
||||
controls_accepted: accept,
|
||||
exit_code: ServiceExitCode::Win32(0),
|
||||
checkpoint: 0,
|
||||
wait_hint: Duration::from_secs(10),
|
||||
process_id: None,
|
||||
})
|
||||
};
|
||||
set(ServiceState::Running, ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN)?;
|
||||
let rt = tokio::runtime::Runtime::new()?;
|
||||
let result = rt.block_on(crate::run(None, None, async {
|
||||
let _ = stop_rx.await;
|
||||
}));
|
||||
set(ServiceState::Stopped, ServiceControlAccept::empty())?;
|
||||
result
|
||||
}
|
||||
Reference in new issue
Block a user