- Every request is authorized before it is handled, including `logs -f`, which skipped the check. - The state root is checked once per process: a second check under Wine moved the live root (and its log) aside. - uninstall removes Program Files after it exits: cmd got a garbled quoted command line; it now runs raw, outside the folder, windowless. - install no longer fails when the first start does; it says how to start. - `proxy-ctl proxy tun on` also turns on proxy.tun.enable. - build-tg-ws-proxy.sh resolves its output path before changing directory. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
321 lines
14 KiB
Rust
321 lines
14 KiB
Rust
//! 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};
|
|
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.";
|
|
|
|
/// 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; 7] = ["proxy-suite-service.exe", "proxy-ctl.exe", "README.md", "THIRD-PARTY.md", "LICENSE", "install.cmd", "uninstall.cmd"];
|
|
|
|
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 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: to.join("proxy-suite-service.exe"),
|
|
launch_arguments: vec![],
|
|
dependencies: vec![],
|
|
account_name: None, // LocalSystem
|
|
account_password: None,
|
|
};
|
|
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 {
|
|
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) },
|
|
]),
|
|
})?;
|
|
if let Err(e) = path::add(&to) {
|
|
println!("warning: could not add {} to PATH: {e:#}", to.display());
|
|
}
|
|
// A moment for the manager to settle the change just made (Wine's otherwise answers
|
|
// ERROR_SERVICE_DATABASE_LOCKED); a start that still fails leaves a working install.
|
|
std::thread::sleep(Duration::from_secs(1));
|
|
match service.start::<&str>(&[]) {
|
|
Ok(()) => println!("{DISPLAY} is installed in {} and started.", to.display()),
|
|
Err(e) => {
|
|
println!("{DISPLAY} is installed in {}, but did not start: {e}", to.display());
|
|
println!("Start it with: sc start {NAME} (its log: %ProgramData%\\ProxySuite\\logs\\service.log)");
|
|
}
|
|
}
|
|
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 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.");
|
|
}
|
|
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. Raw, as cmd
|
|
// does its own quote parsing; from outside the folder, which a working directory holds.
|
|
use std::os::windows::process::CommandExt;
|
|
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
|
let _ = std::process::Command::new("cmd")
|
|
.raw_arg(format!("/c ping -n 3 127.0.0.1 >nul & rmdir /s /q \"{}\"", dir.display()))
|
|
.current_dir(std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into()))
|
|
.creation_flags(CREATE_NO_WINDOW)
|
|
.stdin(std::process::Stdio::null())
|
|
.stdout(std::process::Stdio::null())
|
|
.stderr(std::process::Stdio::null())
|
|
.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<()> {
|
|
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 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 {
|
|
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 = 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: exit,
|
|
checkpoint: 0,
|
|
wait_hint: Duration::from_secs(30),
|
|
process_id: None,
|
|
});
|
|
};
|
|
set(ServiceState::StartPending, ServiceControlAccept::empty(), ServiceExitCode::Win32(0));
|
|
let rt = tokio::runtime::Runtime::new()?;
|
|
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
|
|
}
|