//! The Windows service: registration, and the Service Control Manager's entry point. use std::ffi::OsString; 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."; pub fn install() -> Result<()> { let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE) .context("opening the Service Control Manager (run 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()?, 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")?; 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) }, ]), })?; service.start::<&str>(&[]).context("starting the service")?; println!("{DISPLAY} is installed and started."); Ok(()) } 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)); } } service.delete()?; println!("{DISPLAY} is removed."); Ok(()) } 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) { if let Err(e) = run_service() { tracing::error!("the service failed: {e:#}"); } } fn run_service() -> 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 = |state: ServiceState, accept: ServiceControlAccept| { status.set_service_status(ServiceStatus { service_type: ServiceType::OWN_PROCESS, current_state: state, controls_accepted: accept, exit_code: ServiceExitCode::Win32(0), checkpoint: 0, wait_hint: Duration::from_secs(10), process_id: None, }) }; set(ServiceState::Running, ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN)?; 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())?; result }