Windows: real platform layer, recycle-bin trash backend, cross-compile CI

- squid-core: trash moves behind a platform seam — Windows recycles via
  IFileOperation (shell owns $Recycle.Bin bookkeeping; ledger records no
  physical path there), Unix keeps the rename/copy path untouched
- squid-core: default cleanup anchors per platform; Unix-only helpers
  (getuid, statvfs-style trash dirs, symlink copy) gated
- squid-platform: windows.rs rewritten — installed apps from the uninstall
  registry (HKLM 64/32-bit views + HKCU, SystemComponent/patch filtering),
  BIOS/NT version keys for hardware/OS strings, sysinfo for volumes and
  running processes; winreg replaces the PowerShell stub
- squid-stats: COMPUTERNAME hostname off-unix; battery parsers gated
- CI: .gitlab-ci.yml with a Linux job that cross-checks the whole workspace
  against x86_64-pc-windows-msvc, plus a manual tagged Windows job driven by
  scripts/ci-windows.ps1 (build + test on a real machine)
- host (macOS) tests, clippy -D warnings and fmt stay green
main
mula.liu 2026-10-15 14:56:55 +08:00
parent 4f1022f213
commit 122e81cb4d
14 changed files with 632 additions and 119 deletions

53
.gitlab-ci.yml 100644
View File

@ -0,0 +1,53 @@
# squid CI.
#
# The windows cross-check is the important one for portability: `cargo check`
# against the MSVC target needs no linker and no Windows SDK, so a plain Linux
# runner compiles the entire Windows code path (squid-core recycle bin,
# squid-platform registry adapter, ...) and catches regressions. Real builds
# and test runs happen on the windows-latest runner below, or on any Windows
# machine via `scripts/ci-windows.ps1`.
stages: [check]
variables:
CARGO_TERM_COLOR: always
CARGO_HOME: "$CI_PROJECT_DIR/.cargo"
default:
interruptible: true
rust-lint-test:
stage: check
image: rust:1.85
cache:
key:
files: [Cargo.lock]
paths: [.cargo/registry, .cargo/index, target/]
script:
- rustup component add rustfmt clippy
- cargo fmt --all -- --check
- cargo clippy --workspace --all-targets -- -D warnings
- cargo test --workspace
windows-cross-check:
stage: check
image: rust:1.85
cache:
key:
files: [Cargo.lock]
policy: pull
paths: [.cargo/registry, .cargo/index, target/]
script:
- rustup target add x86_64-pc-windows-msvc
- cargo check --workspace --all-targets --target x86_64-pc-windows-msvc
# Needs a registered Windows GitLab runner (tag: windows). Not required for
# merge until the Windows port is declared stable.
windows-build-test:
stage: check
tags: [windows]
rules:
- when: manual
allow_failure: true
script:
- pwsh -File scripts/ci-windows.ps1

169
Cargo.lock generated
View File

@ -1000,6 +1000,7 @@ dependencies = [
"thiserror",
"toml",
"walkdir",
"windows 0.58.0",
]
[[package]]
@ -1032,7 +1033,9 @@ dependencies = [
"rayon",
"serde",
"squid-core",
"sysinfo",
"walkdir",
"winreg",
]
[[package]]
@ -1144,7 +1147,7 @@ dependencies = [
"memchr",
"ntapi",
"objc2-core-foundation",
"windows",
"windows 0.57.0",
]
[[package]]
@ -1388,7 +1391,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12342cb4d8e3b046f3d80effd474a7a02447231330ef77d71daa6fbc40681143"
dependencies = [
"windows-core 0.57.0",
"windows-targets",
"windows-targets 0.52.6",
]
[[package]]
name = "windows"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6"
dependencies = [
"windows-core 0.58.0",
"windows-targets 0.52.6",
]
[[package]]
@ -1400,7 +1413,20 @@ dependencies = [
"windows-implement 0.57.0",
"windows-interface 0.57.0",
"windows-result 0.1.2",
"windows-targets",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-core"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99"
dependencies = [
"windows-implement 0.58.0",
"windows-interface 0.58.0",
"windows-result 0.2.0",
"windows-strings 0.1.0",
"windows-targets 0.52.6",
]
[[package]]
@ -1413,7 +1439,7 @@ dependencies = [
"windows-interface 0.59.3",
"windows-link",
"windows-result 0.4.1",
"windows-strings",
"windows-strings 0.5.1",
]
[[package]]
@ -1427,6 +1453,17 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "windows-implement"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-implement"
version = "0.60.2"
@ -1449,6 +1486,17 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
@ -1472,7 +1520,16 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8"
dependencies = [
"windows-targets",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-result"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
@ -1484,6 +1541,16 @@ dependencies = [
"windows-link",
]
[[package]]
name = "windows-strings"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10"
dependencies = [
"windows-result 0.2.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-strings"
version = "0.5.1"
@ -1493,13 +1560,22 @@ dependencies = [
"windows-link",
]
[[package]]
name = "windows-sys"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
dependencies = [
"windows-targets 0.48.5",
]
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets",
"windows-targets 0.52.6",
]
[[package]]
@ -1511,34 +1587,67 @@ dependencies = [
"windows-link",
]
[[package]]
name = "windows-targets"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
dependencies = [
"windows_aarch64_gnullvm 0.48.5",
"windows_aarch64_msvc 0.48.5",
"windows_i686_gnu 0.48.5",
"windows_i686_msvc 0.48.5",
"windows_x86_64_gnu 0.48.5",
"windows_x86_64_gnullvm 0.48.5",
"windows_x86_64_msvc 0.48.5",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
"windows_i686_msvc 0.52.6",
"windows_x86_64_gnu 0.52.6",
"windows_x86_64_gnullvm 0.52.6",
"windows_x86_64_msvc 0.52.6",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
@ -1551,24 +1660,48 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
@ -1584,6 +1717,16 @@ dependencies = [
"memchr",
]
[[package]]
name = "winreg"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a277a57398d4bfa075df44f501a17cfdf8542d224f0d36095a2adc7aee4ef0a5"
dependencies = [
"cfg-if",
"windows-sys 0.48.0",
]
[[package]]
name = "zmij"
version = "1.0.23"

View File

@ -301,7 +301,7 @@ Homebrew formula 的校验和。
| --- | --- | --- |
| macOS | 完整实现(规则、App 残留、卷、卸载钩子)| Developer ID 签名与公证流水线 |
| Linux | `squid-platform/src/linux.rs` 已实现 `.desktop` / Flatpak / Snap 应用清单与 XDG 残留目录 | `rules/linux.toml`、真机验证 |
| Windows | `squid-platform/src/windows.rs` 为占位实现 | 注册表卸载表、`%LOCALAPPDATA%` 规则、回收站 API、UAC 提权 |
| Windows | 平台层已实现:注册表卸载表(HKLM 64/32 位 + HKCU)、AppData 残留目录、卷枚举、回收站(`IFileOperation`);CI 每次提交做 MSVC 目标交叉编译检查 | 真机验证、`rules/windows.toml`、UAC 提权、winget 发布 |
其他:规则贡献流程与规则覆盖度基准、TUI 主题自定义、Linux/Windows 冒烟测试。

View File

@ -19,3 +19,10 @@ libc.workspace = true
globset.workspace = true
walkdir.workspace = true
rayon.workspace = true
[target.'cfg(windows)'.dependencies]
windows = { version = "0.58", features = [
"Win32_Foundation",
"Win32_System_Com",
"Win32_UI_Shell",
] }

View File

@ -12,8 +12,12 @@ use crate::paths;
use crate::progress::CancelToken;
use crate::safety::SafetyPolicy;
use rayon::prelude::*;
use std::fs::{File, Metadata, OpenOptions};
use std::io::{self, Read, Write};
use std::fs::Metadata;
#[cfg(not(windows))]
use std::fs::{File, OpenOptions};
use std::io;
#[cfg(not(windows))]
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
@ -297,6 +301,31 @@ fn remove_contents(dir: &Path) -> Result<()> {
/// Roots a cleanup target may legitimately live under when no rule anchors are
/// attached (interactive deletion from the TUI, history restore, …).
pub fn default_anchors() -> Vec<PathBuf> {
#[cfg(windows)]
{
windows_anchors()
}
#[cfg(not(windows))]
unix_default_anchors()
}
#[cfg(windows)]
fn windows_anchors() -> Vec<PathBuf> {
let env = |key: &str| std::env::var_os(key).map(PathBuf::from);
let home = paths::home_dir();
let mut anchors = vec![
env("LOCALAPPDATA").unwrap_or_else(|| home.join("AppData").join("Local")),
env("APPDATA").unwrap_or_else(|| home.join("AppData").join("Roaming")),
env("ProgramData").unwrap_or_else(|| PathBuf::from(r"C:\ProgramData")),
env("TEMP").unwrap_or_else(|| home.join("AppData").join("Local").join("Temp")),
home,
];
anchors.retain(|p| p.exists());
anchors
}
#[cfg(not(windows))]
fn unix_default_anchors() -> Vec<PathBuf> {
let home = paths::home_dir();
let mut anchors = vec![
home.join("Library"),
@ -319,7 +348,25 @@ pub fn default_anchors() -> Vec<PathBuf> {
}
/// Where `path` would land in the Trash, honouring per-volume `.Trashes`.
pub fn trash_target_for(path: &Path) -> PathBuf {
///
/// Returns `None` on Windows: the shell Recycle Bin is written through
/// `IFileOperation`, which does not hand out a destination path, so the
/// ledger records no physical trash location there and undo relies on the
/// Recycle Bin UI.
pub fn trash_target_for(path: &Path) -> Option<PathBuf> {
#[cfg(windows)]
{
let _ = path;
None
}
#[cfg(not(windows))]
{
Some(unix_trash_target_for(path))
}
}
#[cfg(not(windows))]
fn unix_trash_target_for(path: &Path) -> PathBuf {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
@ -340,6 +387,7 @@ pub fn trash_target_for(path: &Path) -> PathBuf {
candidate
}
#[cfg(not(windows))]
fn split_name(name: &str) -> (String, String) {
// Only the last extension of bundles/apps is cosmetic; ".app" stays whole.
if let Some(rest) = name.strip_suffix(".app") {
@ -353,6 +401,7 @@ fn split_name(name: &str) -> (String, String) {
}
}
#[cfg(not(windows))]
fn trash_dir_for(path: &Path) -> PathBuf {
let uid = unsafe { libc::getuid() };
let volume_root = volume_root_for(path);
@ -369,6 +418,7 @@ fn trash_dir_for(path: &Path) -> PathBuf {
paths::home_dir().join(".Trash")
}
#[cfg(not(windows))]
fn can_write(dir: &Path) -> bool {
let probe = dir.join(format!(".squid-probe-{}", std::process::id()));
match OpenOptions::new().create_new(true).write(true).open(&probe) {
@ -380,6 +430,7 @@ fn can_write(dir: &Path) -> bool {
}
}
#[cfg(not(windows))]
fn ensure_dir(dir: &Path) -> bool {
if dir.is_dir() {
return true;
@ -407,10 +458,23 @@ pub fn volume_root_for(path: &Path) -> PathBuf {
}
/// Move to Trash, copying first when the target lives on another volume.
pub fn trash_path(path: &Path) -> Result<PathBuf> {
let destination = trash_target_for(path);
/// The returned path is where the item physically landed, or `None` on
/// Windows where the shell keeps the Recycle Bin bookkeeping.
pub fn trash_path(path: &Path) -> Result<Option<PathBuf>> {
#[cfg(windows)]
{
recycle_bin::move_to_recycle_bin(path)?;
Ok(None)
}
#[cfg(not(windows))]
trash_path_unix(path)
}
#[cfg(not(windows))]
fn trash_path_unix(path: &Path) -> Result<Option<PathBuf>> {
let destination = unix_trash_target_for(path);
match std::fs::rename(path, &destination) {
Ok(()) => Ok(destination),
Ok(()) => Ok(Some(destination)),
Err(_) => {
copy_tree(path, &destination)?;
let kind = if path.is_dir() {
@ -426,11 +490,12 @@ pub fn trash_path(path: &Path) -> Result<PathBuf> {
std::fs::remove_file(path).map_err(|e| SquidError::io(path, e))?;
}
}
Ok(destination)
Ok(Some(destination))
}
}
}
#[cfg(not(windows))]
fn copy_tree(from: &Path, to: &Path) -> Result<()> {
let meta = std::fs::symlink_metadata(from).map_err(|e| SquidError::io(from, e))?;
if meta.file_type().is_symlink() {
@ -556,14 +621,77 @@ mod tests {
}
#[test]
#[cfg(not(windows))]
fn trash_target_avoids_collisions() {
let dir = std::env::temp_dir().join(format!("squid-trash-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let victim = dir.join("victim");
fs::write(&victim, b"hi").unwrap();
let first = trash_target_for(&victim);
let first = trash_target_for(&victim).expect("unix trash targets are predictable");
assert!(first.starts_with(trash_dir_for(&victim)));
let _ = fs::remove_dir_all(&dir);
}
}
/// Windows Recycle Bin backend built on `IFileOperation`. The shell owns the
/// `$Recycle.Bin` bookkeeping (`$I`/`$R` metadata), so squid only asks it to
/// recycle the item and never touches the bin directory itself.
#[cfg(windows)]
mod recycle_bin {
use crate::error::{Result, SquidError};
use std::io;
use std::path::Path;
use windows::core::PCWSTR;
use windows::Win32::Foundation::E_INVALIDARG;
use windows::Win32::Foundation::RPC_E_CHANGED_MODE;
use windows::Win32::System::Com::{
CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_INPROC_SERVER,
COINIT_APARTMENTTHREADED,
};
use windows::Win32::UI::Shell::{
FileOperation, IFileOperation, IShellItem, SHCreateItemFromParsingName, FOF_NOCONFIRMATION,
FOF_NOCONFIRMMKDIR, FOF_NOERRORUI, FOF_SILENT,
};
fn to_wide(value: &str) -> Vec<u16> {
value.encode_utf16().chain(std::iter::once(0)).collect()
}
pub fn move_to_recycle_bin(path: &Path) -> Result<()> {
// IFileOperation needs a COM apartment. The engine deletes from a
// dedicated worker, so we own the lifetime here unless the thread is
// already initialised in a different model.
let init = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
let uninit = init != RPC_E_CHANGED_MODE;
let result = unsafe { recycle_inner(path) };
if uninit {
unsafe { CoUninitialize() };
}
result.map_err(|err| SquidError::Io {
path: path.to_path_buf(),
source: io::Error::from_raw_os_error(err.code().0),
})
}
unsafe fn recycle_inner(path: &Path) -> windows::core::Result<()> {
// IShellItem parsing does not accept verbatim (`\\?\`) paths.
let display = path
.to_str()
.ok_or_else(|| windows::core::Error::from_hresult(E_INVALIDARG))?;
let wide = to_wide(display);
let operation: IFileOperation =
CoCreateInstance(&FileOperation, None, CLSCTX_INPROC_SERVER)?;
operation.SetOperationFlags(
FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR,
)?;
let item = SHCreateItemFromParsingName::<
PCWSTR,
Option<&windows::Win32::System::Com::IBindCtx>,
IShellItem,
>(PCWSTR(wide.as_ptr()), None)?;
operation.DeleteItem(Some(&item), None)?;
operation.PerformOperations()
}
}

View File

@ -342,7 +342,7 @@ fn is_mountpoint(path: &Path) -> bool {
#[cfg(not(target_os = "macos"))]
{
const SKIP: &[&str] = &["/dev", "/proc", "/sys", "/run", "/snap", "/mnt", "/media"];
return SKIP.iter().any(|skip| path.as_os_str() == *skip);
SKIP.iter().any(|skip| path.as_os_str() == *skip)
}
}

View File

@ -106,8 +106,10 @@ pub fn execute(
// Resolve the Trash destination *before* moving so the ledger can
// reverse the move later. `trash_target_for` only invents a name that
// does not exist yet, so this matches what `remove_item_with` does.
// On Windows the shell owns the Recycle Bin bookkeeping and returns
// `None`; restore then falls back to the Recycle Bin UI.
let trash_destination = match job.mode {
DeleteMode::Trash => Some(fs::trash_target_for(&item.path)),
DeleteMode::Trash => fs::trash_target_for(&item.path),
DeleteMode::Permanent => None,
};
@ -125,7 +127,7 @@ pub fn execute(
kind: item.kind,
logical: item.size.0,
allocated: item.allocated.0,
trash_path: trash_destination.filter(|_| job.mode == DeleteMode::Trash),
trash_path: trash_destination,
category: Some(item.category.id().to_string()),
});
}
@ -272,7 +274,12 @@ mod tests {
/// Trash is the default mode, so the undo path has to work end to end:
/// delete → the file leaves its folder and lands in the Trash → `undo`
/// puts it back with its bytes intact.
///
/// Unix-only: on Windows the shell Recycle Bin owns the destination, so
/// the ledger records no physical path and restore goes through the
/// Recycle Bin UI instead of `ledger::restore_session`.
#[test]
#[cfg(unix)]
fn trashing_then_restoring_round_trips_the_file() {
isolate_state();
let dir = scratch_dir("undo");

View File

@ -17,3 +17,7 @@ rayon.workspace = true
[target.'cfg(unix)'.dependencies]
libc.workspace = true
[target.'cfg(windows)'.dependencies]
winreg = "0.52"
sysinfo.workspace = true

View File

@ -12,6 +12,7 @@ use std::path::{Path, PathBuf};
pub mod apps;
pub mod leftovers;
#[cfg(unix)]
pub mod volumes;
#[cfg(target_os = "linux")]
@ -163,7 +164,7 @@ pub fn current() -> Box<dyn Platform> {
}
#[cfg(windows)]
{
Box::new(windows::Windows::default())
Box::new(windows::Windows)
}
#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
{
@ -208,7 +209,8 @@ impl Platform for Unsupported {
}
}
/// Convenience: is this path owned by the effective user?
/// Convenience: can the current user write this path?
#[cfg(not(windows))]
pub fn is_user_writable(path: &Path) -> bool {
use std::os::unix::fs::MetadataExt;
match std::fs::metadata(path) {
@ -223,6 +225,16 @@ pub fn is_user_writable(path: &Path) -> bool {
}
}
/// Windows has no uid; the read-only attribute is the portable signal and
/// ACL checks would need a token walk we cannot afford per path.
#[cfg(windows)]
pub fn is_user_writable(path: &Path) -> bool {
match std::fs::metadata(path) {
Ok(meta) => !meta.permissions().readonly(),
Err(_) => false,
}
}
/// Nearest existing ancestor that exists (for ownership checks on paths that
/// are about to disappear).
pub fn closest_existing(path: &Path) -> PathBuf {

View File

@ -1,39 +1,91 @@
//! Windows adapter (planned). The shape of the implementation is here so the
//! engines already work: apps come from the uninstall registry hive via
//! PowerShell, leftovers from the well known app-data folders.
//! Windows adapter. Installed apps come from the uninstall registry hives
//! (HKLM 64-bit + 32-bit views, HKCU), leftovers from the well-known
//! AppData/ProgramData folders, volumes and processes from `sysinfo`.
use crate::{AppSource, LeftoverRoot, LifecycleReport, Naming, Platform, PlatformId};
use squid_core::progress::CancelToken;
use squid_core::{AppInfo, Bytes, Category, Result, Volume};
use std::path::{Path, PathBuf};
use std::process::Command;
use sysinfo::{Disks, System};
use winreg::enums::{
HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_32KEY, KEY_WOW64_64KEY,
};
use winreg::RegKey;
#[derive(Default)]
pub struct Windows;
fn ps(script: &str) -> Option<String> {
let out = Command::new("powershell")
.args(["-NoProfile", "-NonInteractive", "-Command", script])
.output()
.ok()?;
if out.status.success() {
Some(String::from_utf8_lossy(&out.stdout).to_string())
} else {
None
const UNINSTALL_SUBKEY: &str = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
const NT_VERSION_KEY: &str = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion";
const BIOS_KEY: &str = r"HARDWARE\DESCRIPTION\System\BIOS";
fn open_uninstall_hives() -> Vec<(RegKey, &'static str)> {
let mut hives = Vec::new();
let views = [
(KEY_WOW64_64KEY, "Registry (HKLM 64-bit)"),
(KEY_WOW64_32KEY, "Registry (HKLM 32-bit)"),
];
for (flag, label) in views {
if let Ok(key) = RegKey::predef(HKEY_LOCAL_MACHINE)
.open_subkey_with_flags(UNINSTALL_SUBKEY, KEY_READ | flag)
{
hives.push((key, label));
}
}
if let Ok(key) =
RegKey::predef(HKEY_CURRENT_USER).open_subkey_with_flags(UNINSTALL_SUBKEY, KEY_READ)
{
hives.push((key, "Registry (HKCU)"));
}
hives
}
/// `HKLM\...\Uninstall` + `HKCU\...\Uninstall` + the WOW64 view.
const HARVEST_SCRIPT: &str = r#"
$paths = @(
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*',
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*',
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*'
)
Get-ItemProperty $paths -ErrorAction SilentlyContinue |
Where-Object { $_.DisplayName -and -not $_.SystemComponent } |
ForEach-Object { '{0}|{1}|{2}|{3}' -f $_.DisplayName, $_.DisplayVersion, $_.InstallLocation, $_.UninstallString }
"#;
fn str_value(key: &RegKey, name: &str) -> Option<String> {
key.get_value::<String, _>(name)
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
fn dword_value(key: &RegKey, name: &str) -> Option<u32> {
key.get_value::<u32, _>(name).ok()
}
/// `2024-08-13`-ish epoch millis from the registry's `YYYYMMDD` string.
fn install_date_ms(raw: Option<String>) -> Option<u64> {
let raw = raw?.replace('-', "");
let year: i32 = raw.get(0..4)?.parse().ok()?;
let month: u32 = raw.get(4..6)?.parse().ok()?;
let day: u32 = raw.get(6..8)?.parse().ok()?;
let days = days_since_epoch(year, month, day)?;
Some(days.saturating_mul(86_400_000))
}
/// Days from 1970-01-01 to a proleptic Gregorian date (Howard Hinnant's algorithm).
fn days_since_epoch(y: i32, m: u32, d: u32) -> Option<u64> {
let y = if m <= 2 { y - 1 } else { y };
let era = (if y >= 0 { y } else { y - 399 }) / 400;
let yoe = (y - era * 400) as u64;
let mp = (m + 9) % 12;
let doy = (153 * mp as u64 + 2) / 5 + d as u64 - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
Some((era * 146097 + doe as i32 - 719468) as u64)
}
/// Strip surrounding quotes and `cmd /c` wrappers from an uninstall string.
fn uninstall_program(uninstall_string: &str) -> Option<PathBuf> {
let s = uninstall_string.trim();
let path_part = if s.starts_with('"') {
s.strip_prefix('"')?.split('"').next()?
} else {
// msiexec style: `MsiExec.exe /X{GUID}` — take the first token only if
// it looks like a file; `msiexec` alone resolves via PATH anyway.
s.split_whitespace().next()?
};
let candidate = PathBuf::from(path_part);
candidate.exists().then_some(candidate)
}
impl Platform for Windows {
fn id(&self) -> PlatformId {
@ -43,60 +95,126 @@ impl Platform for Windows {
"Windows".into()
}
fn os_version(&self) -> String {
ps("(Get-CimInstance Win32_OperatingSystem).Caption")
.map(|s| s.trim().to_string())
.unwrap_or_else(|| "Windows".into())
let key = RegKey::predef(HKEY_LOCAL_MACHINE)
.open_subkey_with_flags(NT_VERSION_KEY, KEY_READ)
.ok();
match key {
Some(key) => {
let product = str_value(&key, "ProductName").unwrap_or_else(|| "Windows".into());
let display = str_value(&key, "DisplayVersion");
let build = str_value(&key, "CurrentBuildNumber");
let mut out = product;
if let Some(d) = display {
out.push(' ');
out.push_str(&d);
} else if let Some(b) = build {
out.push_str(" (build ");
out.push_str(&b);
out.push(')');
}
out
}
None => "Windows".into(),
}
}
fn hardware_model(&self) -> String {
ps("(Get-CimInstance Win32_ComputerSystem).Model")
.map(|s| s.trim().to_string())
.unwrap_or_default()
let bios = RegKey::predef(HKEY_LOCAL_MACHINE)
.open_subkey_with_flags(BIOS_KEY, KEY_READ)
.ok();
match bios {
Some(key) => {
let vendor = str_value(&key, "SystemManufacturer");
let model = str_value(&key, "SystemProductName");
match (vendor, model) {
(Some(v), Some(m)) if v != m => format!("{v} {m}"),
(_, Some(m)) => m,
(Some(v), _) => v,
(None, None) => String::new(),
}
}
None => String::new(),
}
}
fn app_sources(&self) -> Vec<AppSource> {
["C:\\Program Files", "C:\\Program Files (x86)"]
.iter()
let env = |key: &str| std::env::var_os(key).map(PathBuf::from);
let mut dirs: Vec<PathBuf> = vec![
env("ProgramFiles").unwrap_or_else(|| PathBuf::from(r"C:\Program Files")),
env("ProgramFiles(x86)").unwrap_or_else(|| PathBuf::from(r"C:\Program Files (x86)")),
];
dirs.dedup();
dirs.into_iter()
.filter(|dir| dir.is_dir())
.map(|dir| AppSource {
dir: PathBuf::from(dir),
dir,
label: "Program Files".into(),
depth: 1,
system: true,
})
.filter(|s| s.dir.is_dir())
.collect()
}
fn list_apps(&self, cancel: &CancelToken, _size: bool) -> Result<Vec<AppInfo>> {
let running: Vec<String> = self
.running_executables()
.into_iter()
.map(|p| p.to_lowercase())
.collect();
let mut apps = Vec::new();
let Some(text) = ps(HARVEST_SCRIPT) else {
return Ok(apps);
};
for line in text.lines() {
if cancel.is_cancelled() {
break;
for (hive, source) in open_uninstall_hives() {
let names = hive
.enum_keys()
.filter_map(|name| name.ok())
.collect::<Vec<_>>();
for name in names {
if cancel.is_cancelled() {
return Ok(apps);
}
let Ok(key) = hive.open_subkey(&name) else {
continue;
};
let Some(display_name) = str_value(&key, "DisplayName") else {
continue;
};
if dword_value(&key, "SystemComponent") == Some(1) {
continue;
}
// Servicing entries (patches, update rollups) are not apps.
if matches!(
str_value(&key, "ReleaseType").as_deref(),
Some("Security Update") | Some("Update Rollup") | Some("Hotfix")
) {
continue;
}
let install_location = str_value(&key, "InstallLocation")
.map(|l| l.trim_matches('"').to_string())
.map(PathBuf::from)
.filter(|p| p.is_dir());
let uninstall_string = str_value(&key, "UninstallString");
let path = install_location
.clone()
.or_else(|| uninstall_string.as_deref().and_then(uninstall_program))
.unwrap_or_default();
let running_app = install_location
.as_ref()
.map(|loc| {
let loc = loc.to_string_lossy().to_lowercase();
running.iter().any(|exe| exe.starts_with(&loc))
})
.unwrap_or(false);
apps.push(AppInfo {
name: display_name,
bundle_id: None,
path,
version: str_value(&key, "DisplayVersion"),
size: Bytes::ZERO,
source: source.into(),
running: running_app,
has_sibling_install: false,
publisher: str_value(&key, "Publisher"),
installed_ms: install_date_ms(str_value(&key, "InstallDate")),
});
}
let cols: Vec<&str> = line.split('|').collect();
let Some(name) = cols.first().map(|s| s.trim()).filter(|s| !s.is_empty()) else {
continue;
};
apps.push(AppInfo {
name: name.to_string(),
bundle_id: None,
path: cols
.get(2)
.map(|p| PathBuf::from(p.trim()))
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_default(),
version: cols
.get(1)
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty()),
size: Bytes::ZERO,
source: "Registry".into(),
running: false,
has_sibling_install: false,
publisher: None,
installed_ms: None,
});
}
apps.sort_by_key(|app| app.name.to_lowercase());
Ok(apps)
}
fn leftover_roots(&self) -> Vec<LeftoverRoot> {
@ -124,45 +242,52 @@ impl Platform for Windows {
LifecycleReport::default()
}
fn volumes(&self) -> Result<Vec<Volume>> {
let system_drive = std::env::var("SystemDrive").unwrap_or_else(|_| "C:".into());
let mut out = Vec::new();
let Some(text) = ps(
"Get-PSDrive -PSProvider FileSystem | ForEach-Object { '{0}|{1}|{2}' -f $_.Root, $_.Used, $_.Free }",
) else {
return Ok(out);
};
for line in text.lines() {
let cols: Vec<&str> = line.split('|').collect();
let (Some(root), Some(used), Some(free)) = (cols.first(), cols.get(1), cols.get(2))
else {
continue;
};
let (Ok(used), Ok(free)) = (used.trim().parse::<u64>(), free.trim().parse::<u64>())
else {
continue;
};
let mount = Path::new(root.trim());
let disks = Disks::new_with_refreshed_list();
for disk in &disks {
let mount = disk.mount_point().to_path_buf();
let mount_name = mount.to_string_lossy().trim_end_matches('\\').to_string();
out.push(Volume {
name: root.trim().to_string(),
mount_point: mount.to_path_buf(),
total: Bytes(used + free),
free: Bytes(free),
is_root: root.trim().eq_ignore_ascii_case("C:\\"),
is_removable: false,
filesystem: "ntfs".into(),
name: mount_name.clone(),
mount_point: mount,
total: Bytes(disk.total_space()),
free: Bytes(disk.available_space()),
is_root: mount_name.eq_ignore_ascii_case(&system_drive),
is_removable: disk.is_removable(),
filesystem: disk.file_system().to_string_lossy().into_owned(),
});
}
Ok(out)
}
fn protected_prefixes(&self) -> Vec<PathBuf> {
["C:\\Windows", "C:\\Program Files"]
.iter()
.map(PathBuf::from)
.collect()
let env = |key: &str| std::env::var_os(key).map(PathBuf::from);
let mut prefixes: Vec<PathBuf> = [
env("SystemRoot"),
env("windir"),
env("ProgramFiles"),
env("ProgramFiles(x86)"),
]
.into_iter()
.flatten()
.chain(std::iter::once(PathBuf::from(r"C:\Windows")))
.collect();
prefixes.sort();
prefixes.dedup();
prefixes
}
fn running_executables(&self) -> Vec<String> {
ps("Get-Process | ForEach-Object { $_.Path }")
.map(|text| text.lines().map(str::to_string).collect())
.unwrap_or_default()
let mut system = System::new_with_specifics(
sysinfo::RefreshKind::nothing()
.with_processes(sysinfo::ProcessRefreshKind::everything()),
);
system.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
system
.processes()
.values()
.filter_map(|process| process.exe())
.map(|path| path.to_string_lossy().into_owned())
.collect()
}
fn inspect_path(&self, _path: &Path) -> Option<String> {
None

View File

@ -192,6 +192,7 @@ fn linux_battery() -> Option<Battery> {
})
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn parse_hhmm(text: &str) -> Option<u64> {
let (hours, minutes) = text.split_once(':')?;
let hours: u64 = hours.parse().ok()?;
@ -228,6 +229,7 @@ mod tests {
}
#[test]
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn hhmm_parsing() {
assert_eq!(parse_hhmm("4:12"), Some(252));
assert_eq!(parse_hhmm("0:00"), Some(0));

View File

@ -126,6 +126,7 @@ impl HostInfo {
}
}
#[cfg(unix)]
fn hostname() -> String {
const BUF: usize = 256;
let mut buf = vec![0u8; BUF];
@ -144,6 +145,11 @@ fn hostname() -> String {
}
}
#[cfg(not(unix))]
fn hostname() -> String {
std::env::var("COMPUTERNAME").unwrap_or_else(|_| "localhost".into())
}
/// Seconds → "3d 4h 12m".
pub fn human_uptime(secs: u64) -> String {
let days = secs / 86_400;

View File

@ -475,6 +475,9 @@ pub enum ConfirmAction {
/// dialog closed, no toast, no log, app still installed. One enum makes the
/// "uninstall approved but the plan is missing" state unrepresentable.
#[derive(Clone, Debug)]
// The item list is boxed where the approval is stored; the variants stay
// intentionally plain data for the dialog code.
#[allow(clippy::large_enum_variant)]
pub enum Approval {
Items {
items: Vec<CleanupItem>,

View File

@ -0,0 +1,23 @@
# Build and test squid on a real Windows machine (runner or dev box).
# Usage: pwsh -File scripts/ci-windows.ps1 [-Static]
param(
# Statically link the CRT so the exe needs no VC++ redistributable.
[switch]$Static
)
$ErrorActionPreference = 'Stop'
if ($Static) {
$env:RUSTFLAGS = '-C target-feature=+crt-static'
}
rustup target add x86_64-pc-windows-msvc | Out-Null
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace
cargo build --release -p squid-cli --target x86_64-pc-windows-msvc
$exe = "target\x86_64-pc-windows-msvc\release\squid.exe"
if (-not (Test-Path $exe)) { throw "missing $exe" }
& $exe --version
Write-Host "windows CI OK: $((Get-Item $exe).Length) bytes" -ForegroundColor Green