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:
faumarayandClaude Opus 5.5 committed 2026-10-26 23:13:19 +03:00
1 parent 918cdc9a75
commit 41c8ed4406
25 files changed
+5411 -7

No files matched your search

+127
View File
@@ -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!()
}