Files
proxy-suite-flake/windows/crates/ps-service/src/main.rs
T
faumarayandClaude Opus 5.5 2c4cdee7d3 windows: AmneziaWG outbounds, and WARP through wireproxy
- ps_core::awg: upstream's scripts/amneziawg_config.py, ported: a profile
  from a .conf, an AmneziaVPN vpn:// link (qCompress'd JSON or the compact
  .conf form, containers and DNS placeholders as upstream reads them) or
  declarative settings (with obfuscationFile's secrets); AWG 3's MTU
  default, the endpoint override, upstream's checks (no wg-quick hooks
  unless allowed, no control characters, one [Interface]); and the
  wireproxy configuration. Checked against links made by upstream's own
  encoder, output byte for byte.
- wireproxy-awg for Windows, built from upstream's tag (pinned to its
  commit) with upstream's patches, by tools/build-wireproxy-awg.sh; in
  the release as a bundled component. Go joins the dev shell.
- The service runs one per "userspace" AmneziaWG outbound and WARP
  device, on its loopback port with the hop login, its configuration
  below the protected state root; "singBox" profiles reach the renderer.
  wireproxy goes direct under the TUN.
- End to end on Linux (an_amneziawg_tunnel): sing-box as the WireGuard
  server, the service's wireproxy as the client; a page through its
  listener and through the proxy's outbound, named inside the tunnel.
- What is still to come and said: AmneziaWG as a system-wide VPN.

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

183 lines
6.5 KiB
Rust

//! 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 awg;
mod clash;
mod components;
mod fetch;
mod install;
#[cfg(windows)]
mod job;
mod paths;
mod service;
mod ssh;
mod store;
mod tg;
mod tor;
mod units;
mod warp;
#[cfg(windows)]
mod winsvc;
mod zapret;
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,
/// For building a release: fetch and verify every component into DIR.
#[command(hide = true)]
StageComponents {
#[arg(long)]
to: PathBuf,
#[arg(long)]
cache: PathBuf,
only: Vec<String>,
},
}
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. `ready` is called once the API
/// listens.
pub async fn run(
state_dir: Option<PathBuf>,
socket: Option<String>,
ready: impl FnOnce(),
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);
paths.create_all().with_context(|| format!("creating {}", paths.root.display()))?;
// The components the release carries, next to the program, into bin\ when they are newer.
if let Some(dir) = install::bundled_components_dir() {
for note in install::seed(&dir, &paths.bin()) {
tracing::info!("{note}");
}
}
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());
ready();
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::register_warp(&shared).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(())
}
/// `logs\service.log`, started over (one old one kept) past 5 MiB.
fn service_log(dir: &std::path::Path) -> std::io::Result<std::fs::File> {
let path = dir.join("service.log");
if std::fs::metadata(&path).is_ok_and(|m| m.len() > 5 * 1024 * 1024) {
let _ = std::fs::rename(&path, dir.join("service.log.1"));
}
std::fs::OpenOptions::new().create(true).append(true).open(path)
}
fn main() -> Result<()> {
let args = Args::parse();
let filter = || tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into());
let as_service = cfg!(windows) && !args.console && args.command.is_none();
if as_service {
// Under the Service Control Manager nothing reads stderr: the log is a file.
let paths = args.state_dir.clone().map(paths::Paths::new).unwrap_or_else(paths::Paths::platform_default);
let file = paths.create_all().ok().and_then(|()| service_log(&paths.logs()).ok());
match file {
Some(f) => tracing_subscriber::fmt().with_env_filter(filter()).with_ansi(false).with_writer(std::sync::Mutex::new(f)).init(),
None => tracing_subscriber::fmt().with_env_filter(filter()).with_writer(std::io::stderr).init(),
}
} else {
tracing_subscriber::fmt().with_env_filter(filter()).with_writer(std::io::stderr).init();
}
if let Some(Command::StageComponents { to, cache, only }) = &args.command {
let _ = rustls::crypto::ring::default_provider().install_default();
let rt = tokio::runtime::Runtime::new()?;
return rt.block_on(install::stage(to, cache, only));
}
match args.command {
#[cfg(windows)]
Some(Command::Install) => return winsvc::install(),
#[cfg(windows)]
Some(Command::Uninstall) => return winsvc::uninstall(),
#[cfg(not(windows))]
Some(Command::Install | Command::Uninstall) => anyhow::bail!("there are no services to install off Windows; use --console"),
Some(Command::StageComponents { .. }) => unreachable!(),
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!()
}