windows: install into Program Files, seed components, log as a service

install copies the release into %ProgramFiles%\ProxySuite (upgrading in
place when the service exists), registers it there, and puts it on the
system PATH: a copy in Downloads could be replaced by any user, and the
service runs it as SYSTEM. uninstall removes the service, the PATH
entry and the program files, and leaves the state.

At every start the service copies the release's components into bin\
when they are newer, staged and verified file by file, and only from a
service running in Program Files. Under the Service Control Manager it
logs to logs\service.log, reports StartPending until the API listens,
and a failed start as a service-specific error.

zapret refuses to start while Flowseal's, the win bundle's or
GoodbyeDPI's service holds WinDivert, and says which to remove.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-27 00:10:26 +03:00
1 parent d1bce9db94
commit 28cc7b2cbe
5 files changed
+338 -36

No files matched your search

+2
View File
@@ -33,5 +33,7 @@ windows-sys = { workspace = true, features = [
"Win32_System_JobObjects",
"Win32_Security_Authorization",
"Win32_Storage_FileSystem",
"Win32_System_Registry",
"Win32_UI_WindowsAndMessaging",
"Win32_System_Threading",
] }
+77
View File
@@ -183,3 +183,80 @@ pub async fn stage(to: &Path, cache: &Path, only: &[String]) -> Result<()> {
}
Ok(())
}
/// Where the release's components are, next to the running program, if it runs from a
/// place only administrators can change (on Windows: Program Files, where `install` puts it).
pub fn bundled_components_dir() -> Option<PathBuf> {
let exe = std::env::current_exe().ok()?;
let dir = exe.parent()?.join("components");
if !dir.is_dir() {
return None;
}
#[cfg(windows)]
{
let program_files = std::env::var_os("ProgramFiles").map(PathBuf::from)?;
if !exe.starts_with(&program_files) {
tracing::warn!("not taking components from {}: the service runs outside Program Files", dir.display());
return None;
}
}
Some(dir)
}
fn copy_tree(from: &Path, to: &Path) -> Result<()> {
std::fs::create_dir_all(to)?;
for entry in std::fs::read_dir(from)? {
let entry = entry?;
let ty = entry.file_type()?;
let dest = to.join(entry.file_name());
if ty.is_dir() {
copy_tree(&entry.path(), &dest)?;
} else if ty.is_file() {
std::fs::copy(entry.path(), &dest)?;
}
}
Ok(())
}
/// Every file `.files.json` names, with its hash.
fn verify_all(dir: &Path) -> Result<()> {
let files: std::collections::BTreeMap<String, String> =
serde_json::from_slice(&std::fs::read(dir.join(".files.json")).context("no .files.json")?)?;
for (rel, want) in files {
if !ps_core::components::safe_relative(&rel) {
bail!("{rel} is not a plain path");
}
let got = hex(&std::fs::read(dir.join(&rel)).with_context(|| format!("{rel} is missing"))?);
if got != want {
bail!("{rel} does not match its recorded hash");
}
}
Ok(())
}
/// Copies each component of `from` (the release's) into `bin` when `bin` lacks it or holds
/// another version: staged, verified file by file, swapped in. What it did, as lines.
pub fn seed(from: &Path, bin: &Path) -> Vec<String> {
let manifest = ps_core::components::manifest();
let mut notes = Vec::new();
for (name, comp) in &manifest.components {
let src = from.join(name);
if installed_version(from, name).as_deref() != Some(comp.version.as_str()) {
continue;
}
if installed_version(bin, name).as_deref() == Some(comp.version.as_str()) {
continue;
}
let staging = bin.join(format!("{name}.staging"));
let _ = std::fs::remove_dir_all(&staging);
let result = copy_tree(&src, &staging).and_then(|()| verify_all(&staging)).and_then(|()| swap(bin, name, &staging));
match result {
Ok(()) => notes.push(format!("installed {name} {} from the release", comp.version)),
Err(e) => {
let _ = std::fs::remove_dir_all(&staging);
notes.push(format!("could not install {name} from the release: {e:#}"));
}
}
}
notes
}
+39 -7
View File
@@ -68,10 +68,23 @@ fn address(arg: Option<String>) -> Address {
}
}
/// 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<()> {
/// 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));
@@ -79,6 +92,7 @@ pub async fn run(state_dir: Option<PathBuf>, socket: Option<String>, shutdown: i
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}");
@@ -109,12 +123,30 @@ pub async fn run(state_dir: Option<PathBuf>, socket: Option<String>, shutdown: i
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();
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()))
.with_writer(std::io::stderr)
.init();
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()?;
@@ -132,7 +164,7 @@ fn main() -> Result<()> {
}
if args.console || !cfg!(windows) {
let rt = tokio::runtime::Runtime::new()?;
return rt.block_on(run(args.state_dir, args.socket, async {
return rt.block_on(run(args.state_dir, args.socket, || {}, async {
let _ = tokio::signal::ctrl_c().await;
}));
}
+5
View File
@@ -159,6 +159,11 @@ impl Service {
self.sup.note(crate::zapret::UNIT, "proxy-suite: zapret runs on Windows only (WinDivert); not started");
return Ok(());
}
#[cfg(windows)]
if let Some((name, what)) = crate::winsvc::windivert_conflict() {
self.sup.stop(crate::zapret::UNIT).await;
anyhow::bail!("the Windows service '{name}' runs DPI bypass with WinDivert already: remove {what}, then turn zapret on again");
}
match cfg.zapret.engine {
ps_core::config::ZapretEngine::DiscordYoutube => {
let program = self.comps.program("zapret", "bin/winws")?;
+215 -29
View File
@@ -1,6 +1,7 @@
//! The Windows service: registration, and the Service Control Manager's entry point.
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::{Context, Result};
@@ -17,24 +18,97 @@ 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.";
/// Where `install` puts the program: only administrators may change it, so what the service
/// runs as SYSTEM, and the components it takes from beside it, stay theirs.
pub fn install_dir() -> PathBuf {
std::env::var_os("ProgramFiles").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(r"C:\Program Files")).join("ProxySuite")
}
/// The files of a release that `install` copies.
const RELEASE_FILES: [&str; 5] = ["proxy-suite-service.exe", "proxy-ctl.exe", "README.md", "THIRD-PARTY.md", "LICENSE"];
fn copy_release(from: &Path, to: &Path) -> Result<()> {
std::fs::create_dir_all(to)?;
for f in RELEASE_FILES {
let src = from.join(f);
if src.is_file() {
std::fs::copy(&src, to.join(f)).with_context(|| format!("copying {f}"))?;
}
}
let comps = from.join("components");
if comps.is_dir() {
let dest = to.join("components");
let _ = std::fs::remove_dir_all(&dest);
copy_dir(&comps, &dest)?;
}
Ok(())
}
fn copy_dir(from: &Path, to: &Path) -> Result<()> {
std::fs::create_dir_all(to)?;
for entry in std::fs::read_dir(from)? {
let entry = entry?;
let dest = to.join(entry.file_name());
if entry.file_type()?.is_dir() {
copy_dir(&entry.path(), &dest)?;
} else {
std::fs::copy(entry.path(), &dest)?;
}
}
Ok(())
}
fn wait_stopped(service: &windows_service::service::Service) -> Result<()> {
for _ in 0..60 {
if service.query_status()?.current_state == ServiceState::Stopped {
return Ok(());
}
std::thread::sleep(Duration::from_millis(500));
}
anyhow::bail!("the service did not stop")
}
/// Installs (or upgrades) the release this program came with: copied into Program Files,
/// registered there to start at boot as LocalSystem, put on the system PATH, started.
pub fn install() -> Result<()> {
let from = std::env::current_exe()?.parent().context("no program directory")?.to_path_buf();
let to = install_dir();
let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE)
.context("opening the Service Control Manager (run as an administrator)")?;
.context("opening the Service Control Manager (run this 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()?,
executable_path: to.join("proxy-suite-service.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")?;
let access = ServiceAccess::QUERY_STATUS | ServiceAccess::STOP | ServiceAccess::START | ServiceAccess::CHANGE_CONFIG;
let service = match manager.open_service(NAME, access) {
Ok(existing) => {
// An upgrade: what runs lets go of its files first.
if existing.query_status()?.current_state != ServiceState::Stopped {
println!("Stopping {DISPLAY}…");
let _ = existing.stop();
wait_stopped(&existing)?;
}
if from != to {
copy_release(&from, &to)?;
}
existing.change_config(&info)?;
existing
}
Err(_) => {
if from != to {
copy_release(&from, &to)?;
}
manager.create_service(&info, access).context("creating the service")?
}
};
service.set_description(DESCRIPTION)?;
// Restarted when it dies, as systemd's Restart=always.
service.update_failure_actions(ServiceFailureActions {
@@ -47,31 +121,128 @@ pub fn install() -> Result<()> {
ServiceAction { action_type: ServiceActionType::Restart, delay: Duration::from_secs(60) },
]),
})?;
if let Err(e) = path::add(&to) {
println!("warning: could not add {} to PATH: {e:#}", to.display());
}
service.start::<&str>(&[]).context("starting the service")?;
println!("{DISPLAY} is installed and started.");
println!("{DISPLAY} is installed in {} and started.", to.display());
println!("Open a new terminal and try: proxy-ctl status");
Ok(())
}
/// Stops and removes the service and takes it off PATH. The configuration and state in
/// ProgramData stay; the program files go once this has exited.
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));
.context("opening the Service Control Manager (run this as an administrator)")?;
if let Ok(service) = manager.open_service(NAME, ServiceAccess::QUERY_STATUS | ServiceAccess::STOP | ServiceAccess::DELETE) {
if service.query_status()?.current_state != ServiceState::Stopped {
let _ = service.stop();
let _ = wait_stopped(&service);
}
service.delete()?;
println!("{DISPLAY} is removed.");
} else {
println!("{DISPLAY} was not installed.");
}
service.delete()?;
println!("{DISPLAY} is removed.");
let dir = install_dir();
let _ = path::remove(&dir);
if dir.exists() {
// This program may be one of the files: they go a moment after it exits.
let _ = std::process::Command::new("cmd")
.args(["/c", "ping -n 3 127.0.0.1 >nul & rmdir /s /q"])
.arg(&dir)
.spawn();
println!("Removing {}.", dir.display());
}
println!("The configuration and state stay in %ProgramData%\\ProxySuite; delete that folder to forget them.");
Ok(())
}
/// The system PATH, in the registry.
mod path {
use std::path::Path;
use anyhow::{Result, bail};
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::System::Registry::{
HKEY, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WRITE, REG_EXPAND_SZ, RegCloseKey, RegOpenKeyExW, RegQueryValueExW, RegSetValueExW,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{HWND_BROADCAST, SMTO_ABORTIFHUNG, SendMessageTimeoutW, WM_SETTINGCHANGE};
const KEY: &str = r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(Some(0)).collect()
}
fn with_path(edit: impl FnOnce(&mut Vec<String>)) -> Result<()> {
// SAFETY: NUL-terminated names; the key is closed below; buffers are as long as said.
unsafe {
let mut key: HKEY = std::ptr::null_mut();
if RegOpenKeyExW(HKEY_LOCAL_MACHINE, wide(KEY).as_ptr(), 0, KEY_READ | KEY_WRITE, &mut key) != ERROR_SUCCESS {
bail!("cannot open the environment's registry key");
}
let name = wide("Path");
let mut len = 0u32;
let mut kind = 0u32;
RegQueryValueExW(key, name.as_ptr(), std::ptr::null_mut(), &mut kind, std::ptr::null_mut(), &mut len);
let mut buf = vec![0u16; (len as usize / 2) + 1];
let mut len2 = (buf.len() * 2) as u32;
if RegQueryValueExW(key, name.as_ptr(), std::ptr::null_mut(), &mut kind, buf.as_mut_ptr() as *mut u8, &mut len2) != ERROR_SUCCESS {
RegCloseKey(key);
bail!("cannot read the system PATH");
}
let text = String::from_utf16_lossy(&buf[..(len2 as usize / 2)]).trim_end_matches('\0').to_owned();
let mut parts: Vec<String> = text.split(';').filter(|p| !p.is_empty()).map(str::to_owned).collect();
edit(&mut parts);
let new: Vec<u16> = wide(&parts.join(";"));
let rc = RegSetValueExW(key, name.as_ptr(), 0, REG_EXPAND_SZ, new.as_ptr() as *const u8, (new.len() * 2) as u32);
RegCloseKey(key);
if rc != ERROR_SUCCESS {
bail!("cannot write the system PATH");
}
// New terminals see it without a sign-out.
let env = wide("Environment");
SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, env.as_ptr() as isize, SMTO_ABORTIFHUNG, 2000, std::ptr::null_mut());
}
Ok(())
}
pub fn add(dir: &Path) -> Result<()> {
let d = dir.to_string_lossy().into_owned();
with_path(|parts| {
if !parts.iter().any(|p| p.eq_ignore_ascii_case(&d)) {
parts.push(d);
}
})
}
pub fn remove(dir: &Path) -> Result<()> {
let d = dir.to_string_lossy().into_owned();
with_path(|parts| parts.retain(|p| !p.eq_ignore_ascii_case(&d)))
}
}
/// A running service that holds WinDivert for DPI bypass already: Flowseal's `service.bat`
/// installs "zapret", bol-van's bundle "winws1"/"winws2", and GoodbyeDPI its own. Two such
/// filters fight over the same packets (and winws refuses a duplicate filter).
pub fn windivert_conflict() -> Option<(&'static str, &'static str)> {
const KNOWN: [(&str, &str); 4] = [
("zapret", "Flowseal's zapret-discord-youtube service (service.bat → Remove Services)"),
("winws1", "zapret-win-bundle's winws1 service (service_del.cmd)"),
("winws2", "zapret-win-bundle's winws2 service (service_del.cmd)"),
("GoodbyeDPI", "GoodbyeDPI's service (its service_remove.cmd)"),
];
let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT).ok()?;
KNOWN.into_iter().find(|(name, _)| {
manager
.open_service(name, ServiceAccess::QUERY_STATUS)
.and_then(|s| s.query_status())
.is_ok_and(|st| st.current_state != ServiceState::Stopped)
})
}
define_windows_service!(ffi_service_main, service_main);
pub fn dispatch() -> Result<()> {
@@ -85,6 +256,14 @@ fn service_main(_args: Vec<OsString>) {
}
fn run_service() -> Result<()> {
let result = run_service_inner();
if let Err(e) = &result {
tracing::error!("{e:#}");
}
result
}
fn run_service_inner() -> Result<()> {
let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>();
let mut stop_tx = Some(stop_tx);
let handler = move |control| match control {
@@ -98,22 +277,29 @@ fn run_service() -> Result<()> {
_ => ServiceControlHandlerResult::NotImplemented,
};
let status = service_control_handler::register(NAME, handler)?;
let set = |state: ServiceState, accept: ServiceControlAccept| {
status.set_service_status(ServiceStatus {
let set = move |state: ServiceState, accept: ServiceControlAccept, exit: ServiceExitCode| {
let _ = status.set_service_status(ServiceStatus {
service_type: ServiceType::OWN_PROCESS,
current_state: state,
controls_accepted: accept,
exit_code: ServiceExitCode::Win32(0),
exit_code: exit,
checkpoint: 0,
wait_hint: Duration::from_secs(10),
wait_hint: Duration::from_secs(30),
process_id: None,
})
});
};
set(ServiceState::Running, ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN)?;
set(ServiceState::StartPending, ServiceControlAccept::empty(), ServiceExitCode::Win32(0));
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())?;
let result = rt.block_on(crate::run(
None,
None,
|| set(ServiceState::Running, ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN, ServiceExitCode::Win32(0)),
async {
let _ = stop_rx.await;
},
));
// A start that failed is one the Service Control Manager reports, not a clean stop.
let exit = if result.is_ok() { ServiceExitCode::Win32(0) } else { ServiceExitCode::ServiceSpecific(1) };
set(ServiceState::Stopped, ServiceControlAccept::empty(), exit);
result
}