The state directory gets a protected DACL (SYSTEM and Administrators) at every start; on Windows programs run only from its bin\, never from PATH; rule-set and geodata names are validated before they become file names, and checked again where they do; logs need the secrets scope. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
395 lines
16 KiB
Rust
395 lines
16 KiB
Rust
//! 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;
|
|
// A tag becomes a file name: the configuration is validated, but this writes as SYSTEM.
|
|
let safe = |tag: &str| !tag.is_empty() && !tag.starts_with('.') && tag.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '!' | '@' | '.' | '_' | '-'));
|
|
for w in wanted.iter().filter(|w| w.dns_copy_of.is_none()) {
|
|
if !safe(&w.tag) {
|
|
results.push((w.tag.clone(), Err("not a name a file may have".into())));
|
|
continue;
|
|
}
|
|
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();
|
|
if !safe(&w.tag) || !safe(of) {
|
|
continue;
|
|
}
|
|
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;
|
|
}
|
|
}
|
|
}
|