From fdff5fb238e54f7b7a392c4fef674b99bc8f0ee3 Mon Sep 17 00:00:00 2001 From: NitroDiesel <228459919+NitroDiesel@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:03:36 +0800 Subject: [PATCH 1/3] Add Windows support Rufust now runs natively on Windows 10 and 11 (x64) alongside Linux. The interface, planner, helper protocol, image analysis, Windows-media layout, answer files, and boot records are shared; device discovery, privilege, and the disk engine have Windows implementations. - Discovery enumerates disk interfaces with zero-access storage IOCTLs and protects the disk holding Windows, the system partition, page files, and spanned volumes; virtual disks are never listed. Hot-plug polls disks and volumes. - The window never runs as administrator. Each operation runs in an elevated copy of rufust.exe, approved through UAC, that serves one request over two private named pipes and is accepted only by its process ID. Cancellation is a line on the control pipe. - The engine revalidates the target, locks and dismounts its volumes, partitions with the disk IOCTLs, formats with Windows' FormatEx and a built-in large-FAT32 formatter (after upstream's FormatLargeFAT32), decodes gzip/bzip2/xz/lzma/zstd/zip in process, attaches VHD/VHDX read-only, builds Windows installer media with UEFI:NTFS and BIOS boot records, and verifies. - Desktop integration: the common Open dialog, the app-mode theme, %APPDATA% settings, regional options from Windows, and an embedded Rufus icon with an asInvoker manifest. - Linux code is gated, not changed; shared progress code moved to engine.rs. An elevated script tests the engine end to end on throwaway VHDX disks, and CI and the release workflow gain Windows jobs producing a portable zip. The README, project context, capability matrix, safety, architecture, building, and a new Windows document describe the port. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 27 + .github/workflows/release.yml | 38 +- AGENTS.md | 9 +- CONTRIBUTING.md | 15 +- Cargo.lock | 172 ++- README.md | 46 +- THIRD_PARTY.md | 20 +- apps/rufust/Cargo.toml | 24 +- apps/rufust/build.rs | 87 ++ apps/rufust/src/desktop.rs | 141 ++ apps/rufust/src/helper_client.rs | 401 +----- apps/rufust/src/helper_client/linux.rs | 376 ++++++ apps/rufust/src/helper_client/windows.rs | 486 +++++++ apps/rufust/src/hotplug.rs | 32 +- apps/rufust/src/image_inspection.rs | 62 +- apps/rufust/src/main.rs | 70 +- apps/rufust/src/regional.rs | 90 +- apps/rufust/src/settings.rs | 18 +- apps/rufust/src/state.rs | 47 +- apps/rufust/ui/appwindow.slint | 5 +- crates/rufust-core/src/device.rs | 11 +- crates/rufust-core/src/plan.rs | 16 +- crates/rufust-core/src/safety.rs | 14 +- crates/rufust-helper-protocol/src/lib.rs | 17 +- crates/rufust-helper/Cargo.toml | 21 +- crates/rufust-helper/src/engine.rs | 140 ++ crates/rufust-helper/src/fat32.rs | 345 +++++ crates/rufust-helper/src/lib.rs | 132 +- crates/rufust-helper/src/main.rs | 35 +- crates/rufust-helper/src/udisks_engine.rs | 122 +- crates/rufust-helper/src/windows/disk.rs | 516 ++++++++ crates/rufust-helper/src/windows/format.rs | 228 ++++ crates/rufust-helper/src/windows/mod.rs | 1132 +++++++++++++++++ crates/rufust-helper/src/windows/pipe.rs | 116 ++ crates/rufust-helper/src/windows/source.rs | 529 ++++++++ crates/rufust-helper/src/windows/vhd_tests.rs | 412 ++++++ crates/rufust-helper/src/windows_media.rs | 39 +- crates/rufust-image/src/lib.rs | 15 +- crates/rufust-platform/Cargo.toml | 14 +- crates/rufust-platform/src/lib.rs | 67 +- crates/rufust-platform/src/windows.rs | 867 +++++++++++++ docs/ARCHITECTURE.md | 23 +- docs/BUILDING.md | 29 +- docs/CAPABILITIES.md | 38 +- docs/PROJECT_CONTEXT.md | 76 +- docs/SAFETY.md | 34 +- docs/WINDOWS.md | 149 +++ packaging/windows/README.txt | 38 + scripts/windows/vhd-tests.ps1 | 81 ++ 49 files changed, 6749 insertions(+), 673 deletions(-) create mode 100644 apps/rufust/src/desktop.rs create mode 100644 apps/rufust/src/helper_client/linux.rs create mode 100644 apps/rufust/src/helper_client/windows.rs create mode 100644 crates/rufust-helper/src/engine.rs create mode 100644 crates/rufust-helper/src/fat32.rs create mode 100644 crates/rufust-helper/src/windows/disk.rs create mode 100644 crates/rufust-helper/src/windows/format.rs create mode 100644 crates/rufust-helper/src/windows/mod.rs create mode 100644 crates/rufust-helper/src/windows/pipe.rs create mode 100644 crates/rufust-helper/src/windows/source.rs create mode 100644 crates/rufust-helper/src/windows/vhd_tests.rs create mode 100644 crates/rufust-platform/src/windows.rs create mode 100644 docs/WINDOWS.md create mode 100644 packaging/windows/README.txt create mode 100644 scripts/windows/vhd-tests.ps1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 098451a..95d6d04 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,6 +70,33 @@ jobs: - name: Helper smoke test run: target/release/rufust-helper --dry-run /dev/null + windows: + name: Windows + runs-on: windows-2022 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: dtolnay/rust-toolchain@bc540ba06a4ccee415bb241490e0b25ee8e7d315 + with: + components: rustfmt, clippy + - name: Test + run: cargo test --workspace --locked + - name: Lint + run: cargo clippy --workspace --all-targets --locked -- -D warnings + - name: Release build + run: cargo build --workspace --release --locked + - name: Helper smoke test + run: target\release\rufust-helper.exe --dry-run + - name: Desktop version + shell: pwsh + run: | + $version = & target\release\rufust.exe --version | Out-String + if ($version.Trim() -notmatch '^rufust \d+\.\d+\.\d+$') { throw "unexpected version: $version" } + # Runners are elevated, so the engine can be exercised end to end on + # disposable VHDX disks; the tests refuse any other disk. + - name: Virtual disk integration + shell: pwsh + run: powershell -NoProfile -ExecutionPolicy Bypass -File scripts\windows\vhd-tests.ps1 + distro-builds: runs-on: ubuntu-24.04 strategy: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6dc0ee3..d7f280b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -295,12 +295,44 @@ jobs: dist/*.AppImage.zsync if-no-files-found: error + windows: + name: Windows portable build + runs-on: windows-2022 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: dtolnay/rust-toolchain@bc540ba06a4ccee415bb241490e0b25ee8e7d315 + - name: Build + run: cargo build -p rufust --release --locked + - name: Package and validate + shell: pwsh + run: | + $name = "rufust-$env:PACKAGE_VERSION-windows-x86_64" + New-Item -ItemType Directory -Path dist, $name | Out-Null + Copy-Item target\release\rufust.exe $name + Copy-Item packaging\windows\README.txt, LICENSE.txt, THIRD_PARTY.md $name + $version = & "$name\rufust.exe" --version | Out-String + if ($version.Trim() -ne "rufust $env:PACKAGE_VERSION") { + throw "unexpected version: $version" + } + # x86-64 PE with an asInvoker manifest: the window never elevates. + $bytes = [IO.File]::ReadAllBytes((Resolve-Path "$name\rufust.exe").Path) + $pe = [BitConverter]::ToInt32($bytes, 0x3c) + if ([BitConverter]::ToUInt16($bytes, $pe + 4) -ne 0x8664) { throw 'not x86-64' } + $text = [Text.Encoding]::ASCII.GetString($bytes) + if (-not $text.Contains('level="asInvoker"')) { throw 'missing asInvoker manifest' } + Compress-Archive -Path $name -DestinationPath "dist\$name.zip" + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: installer-windows + path: dist/*.zip + if-no-files-found: error + publish: name: Publish GitHub Release if: >- startsWith(github.ref, 'refs/tags/') || startsWith(github.ref, 'refs/heads/release/v') - needs: [debian, fedora, arch, appimage] + needs: [debian, fedora, arch, appimage, windows] runs-on: ubuntu-24.04 permissions: contents: write @@ -333,7 +365,7 @@ jobs: fi version="${tag#v}" cat > /tmp/release-notes.md <<'EOF' - Rufust is a stable Linux-native release within its documented + Rufust is a stable Linux and Windows release within its documented capability set. It is an independent port and is not produced, endorsed, or supported by the upstream Rufus project. @@ -348,6 +380,8 @@ jobs: - Fedora: `sudo dnf install ./rufust-*.x86_64.rpm` - Arch Linux: `sudo pacman -U ./rufust-*-x86_64.pkg.tar.zst` - Portable desktop: `chmod +x ./rufust-*.AppImage && ./rufust-*.AppImage` + - Windows 10/11 (x64): extract `rufust-*-windows-x86_64.zip` and run + `rufust.exe`; Windows asks for administrator approval at Start. The AppImage runs on x86_64 glibc 2.28+ desktops. If FUSE is not available, add `--appimage-extract-and-run`. For security, the diff --git a/AGENTS.md b/AGENTS.md index 91dc9a5..f9f4e79 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,13 +12,20 @@ releases, or UI behavior, also read the branch-specific document named in the context file before editing. Completion means the implementation, capability matrix, project context, and verification evidence agree. +Rufust ships on Linux and Windows. Platform code lives in `windows` and Linux +modules beside shared code; read [`docs/WINDOWS.md`](docs/WINDOWS.md) before +changing Windows behavior, and keep both builds passing (`cargo clippy +--workspace --all-targets -- -D warnings` on each). A change to shared code is +not done until it works on both. + ## UI work Use the `frontend-design` skill and a bounded UI review subagent when those capabilities are available. Preserve the compact Device Workbench direction, original Rufus icon assets, keyboard access, true modal blocking, and verified light/dark layouts. Visually test the smallest supported window and a maximized -window before declaring UI work complete. +window before declaring UI work complete, on Linux and on Windows when the +change can render differently there. ## Commit attribution diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 997992c..fa1ddc2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,15 +8,18 @@ cargo build cargo run -p rufust ``` -The desktop has no environment-variable bypass for destructive writes. A live -operation is available only through the installed polkit policy and -`/usr/libexec/rufust-helper`. Use the helper's `--dry-run` mode for request -validation and disposable loop devices for integration tests. Never test on a -disk containing useful data. +The desktop has no environment-variable bypass for destructive writes. On +Linux, a live operation is available only through udisks2 or the installed +polkit policy and `/usr/libexec/rufust-helper`; on Windows, only through the +UAC-elevated worker. Use the helper's `--dry-run` mode for request validation, +disposable loop devices for Linux integration tests, and +`scripts/windows/vhd-tests.ps1` (elevated) for throwaway VHDX disks on +Windows. Never test on a disk containing useful data. ## Safety rules -- Keep raw-disk I/O out of the desktop process. +- Keep raw-disk I/O out of the desktop process, and never run the window as + root or administrator. - Revalidate device identity in the helper before the first write. - Prefer fixed absolute tool paths; never shell out with user-controlled commands. - Document unavailable Windows-only features honestly (see `docs/CAPABILITIES.md`). diff --git a/Cargo.lock b/Cargo.lock index ec9f8cb..0913c77 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -580,6 +580,15 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "bzip2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c" +dependencies = [ + "libbz2-rs-sys", +] + [[package]] name = "calloop" version = "0.13.0" @@ -1074,6 +1083,20 @@ version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" +[[package]] +name = "embed-resource" +version = "3.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f" +dependencies = [ + "cc", + "memchr", + "rustc_version", + "toml 1.2.1+spec-1.1.0", + "vswhom", + "winreg", +] + [[package]] name = "endi" version = "1.1.1" @@ -1114,7 +1137,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -1665,6 +1688,12 @@ dependencies = [ "rayon", ] +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + [[package]] name = "heck" version = "0.5.0" @@ -2037,12 +2066,12 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.7.1" +version = "2.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c9c992b02b5b4c94ea26e32fe5bccb7aa7d9f390ab5c1221ff895bc7ea8b652" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", - "hashbrown 0.15.5", + "hashbrown 0.17.1", ] [[package]] @@ -2231,6 +2260,12 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" +[[package]] +name = "libbz2-rs-sys" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32f454fd6831a29c0e827ed075bca2a15be201bd57f4168f0fd1041124eab17e" + [[package]] name = "libc" version = "0.2.189" @@ -2370,6 +2405,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "lzma-rust2" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e20f57f9918e5bd7bc58c22cdd70a6afc7375d4dd9683af5f2b34bd3d2bba619" +dependencies = [ + "sha2", +] + [[package]] name = "md-5" version = "0.10.6" @@ -3278,6 +3322,7 @@ name = "rufust" version = "1.1.0" dependencies = [ "ashpd", + "embed-resource", "i-slint-backend-winit", "libc", "pollster", @@ -3288,6 +3333,7 @@ dependencies = [ "rufust-platform", "slint", "slint-build", + "windows-sys 0.59.0", ] [[package]] @@ -3319,14 +3365,19 @@ dependencies = [ name = "rufust-helper" version = "1.1.0" dependencies = [ + "bzip2", + "flate2", "fs2", "libc", + "lzma-rust2", "rufust-core", "rufust-helper-protocol", "rufust-image", "rufust-platform", + "ruzstd", "sha2", "thiserror 2.0.19", + "windows-sys 0.59.0", "zbus", ] @@ -3361,6 +3412,7 @@ name = "rufust-platform" version = "1.1.0" dependencies = [ "rufust-core", + "windows-sys 0.59.0", ] [[package]] @@ -3388,7 +3440,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.4.15", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -3401,7 +3453,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3446,6 +3498,12 @@ dependencies = [ "unicode-script", ] +[[package]] +name = "ruzstd" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fad02996bfc73da3e301efe90b1837be9ed8f4a462b6ed410aa35d00381de89f" + [[package]] name = "same-file" version = "1.0.6" @@ -3555,6 +3613,15 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + [[package]] name = "sha1" version = "0.10.7" @@ -3650,7 +3717,7 @@ dependencies = [ "regex", "serde_json", "tar", - "toml", + "toml 0.8.23", ] [[package]] @@ -3926,10 +3993,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix 1.1.4", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4059,11 +4126,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" dependencies = [ "serde", - "serde_spanned", - "toml_datetime", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", "toml_edit", ] +[[package]] +name = "toml" +version = "1.2.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned 1.1.3", + "toml_datetime 1.1.3+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 1.0.5", +] + [[package]] name = "toml_datetime" version = "0.6.11" @@ -4073,6 +4155,15 @@ dependencies = [ "serde", ] +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + [[package]] name = "toml_edit" version = "0.22.27" @@ -4081,10 +4172,19 @@ checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" dependencies = [ "indexmap", "serde", - "serde_spanned", - "toml_datetime", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", "toml_write", - "winnow", + "winnow 0.7.15", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow 1.0.5", ] [[package]] @@ -4093,6 +4193,12 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + [[package]] name = "tracing" version = "0.1.44" @@ -4316,6 +4422,26 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vswhom" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b" +dependencies = [ + "libc", + "vswhom-sys", +] + +[[package]] +name = "vswhom-sys" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150" +dependencies = [ + "cc", + "libc", +] + [[package]] name = "vtable" version = "0.2.1" @@ -4588,7 +4714,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] @@ -4938,6 +5064,22 @@ dependencies = [ "memchr", ] +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "winreg" +version = "0.56.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" +dependencies = [ + "cfg-if", + "windows-sys 0.61.2", +] + [[package]] name = "wio" version = "0.2.2" diff --git a/README.md b/README.md index a3c4775..26e5c90 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Rufust -Rufust is an **independent, community-built Linux port inspired by Rufus**. It provides a native desktop workflow for inspecting, formatting, and writing removable media. It is not produced, endorsed, or supported by the upstream Rufus project or its maintainers. +Rufust is an **independent, community-built Linux and Windows port inspired by Rufus**. It provides a native desktop workflow for inspecting, formatting, and writing removable media. It is not produced, endorsed, or supported by the upstream Rufus project or its maintainers. > **Destructive operation warning** > @@ -14,7 +14,7 @@ Rufust is an **independent, community-built Linux port inspired by Rufus**. It p ## Project status -Rufust is a Linux-native implementation, not a rebuild of the Windows executable. It creates: +Rufust is a native implementation for Linux and Windows 10/11, written in Rust; it is not a rebuild of the upstream Windows executable. On both systems it creates: - Windows 10/11 installer drives from Windows ISOs. Files over 4 GB are supported through NTFS and the Secure Boot signed UEFI:NTFS loader, with BIOS boot records on MBR. - Bootable drives from ISOHybrid Linux ISOs, raw and compressed disk images, and VHD/VHDX. @@ -22,13 +22,14 @@ Rufust is a Linux-native implementation, not a rebuild of the Windows executable Options that still need an unfinished workflow are recognized and blocked with a direct reason. These include non-hybrid Linux ISOs, FreeDOS, Windows To Go, and persistence. [PARITY.md](docs/PARITY.md) tracks every upstream Rufus feature, and the [capability matrix](docs/CAPABILITIES.md) is the authority for each release. -The goal is output compatibility where Linux has a safe, maintained implementation. It is not to emulate Windows internals with unsafe shortcuts. +The goal is output compatibility where each platform has a safe, maintained implementation. It is not to emulate Windows internals with unsafe shortcuts on Linux. On Windows, ext2/3/4 and ReFS creation are not offered; everything else above works the same. ## Current product direction -- Native Slint desktop interface on Wayland and X11, with light and dark themes. +- Native Slint desktop interface on Wayland, X11, and Windows, with light and dark themes that follow the system. - Automatic sysfs-backed device discovery with mount and device-holder safety checks. - Plug and play: writes go through the system udisks2 service, so nothing extra has to be installed. A small polkit-authorized helper is the fallback. +- On Windows: a single portable `rufust.exe`. The window stays unprivileged; each operation runs in an elevated worker after one UAC approval, using Windows' own partitioning and file system providers plus a built-in large-FAT32 formatter. - MBR/GPT partitioning, raw image writing, verification, and common Linux/portable filesystems. - ISO/ISOHybrid and compressed-image analysis with clear compatibility and safety feedback. - Logged, cancellable operations with a final flush before a device is reported ready. @@ -37,7 +38,7 @@ The visual language is intentionally based on the physical act of preparing medi ## Build and run -The application is written in Rust with Slint. Slint renders the interface while the platform backend integrates with native Wayland or X11 windows, input, fonts, accessibility, and the desktop theme. +The application is written in Rust with Slint. Slint renders the interface while the platform backend integrates with native Wayland, X11, or Windows windows, input, fonts, accessibility, and the desktop theme. ### Debian or Ubuntu @@ -66,11 +67,25 @@ cargo build cargo run ``` +### Windows + +Install [Rust](https://rustup.rs/) with the MSVC toolchain and Visual Studio +Build Tools ("Desktop development with C++"). No other libraries are needed. + +```powershell +cargo build --release -p rufust +target\release\rufust.exe +``` + +Run the window as yourself, never "as administrator": Windows asks for +approval at Start, and only the disk work runs elevated. See +[Windows](docs/WINDOWS.md) for the design and the virtual-disk test script. + For the full formatter and image-tool set, install the runtime dependencies listed in [Building and packaging](docs/BUILDING.md). During development, raw writes should be tested against disposable image files or loop devices, never a disk containing useful data. ## Install a release -Download the package for your x86_64 distribution from +Download the package for your x86_64 distribution, or the Windows zip, from [GitHub Releases](https://github.com/NitroDiesel/rufust/releases). Keep `SHA256SUMS` beside the downloaded package and verify it before installing: @@ -109,6 +124,21 @@ polkit policy, desktop metadata, and required runtime dependencies. Each release is stable within its documented capability set; review the [capability matrix](docs/CAPABILITIES.md) before writing to removable media. +### Windows + +Download `rufust-*-windows-x86_64.zip` (Windows 10/11, x64), check it against +`SHA256SUMS`, extract it, and run `rufust.exe`. Nothing is installed. + +```powershell +Get-FileHash .\rufust-*-windows-x86_64.zip -Algorithm SHA256 +``` + +The window runs with your normal rights. When you confirm an operation, +Windows asks once for administrator approval, and a separate elevated copy of +`rufust.exe` does the disk work; declining writes nothing. The executable is +not code-signed yet, so SmartScreen may ask you to confirm the first launch. +Windows builds are published from the first release after 1.1.0. + `SHA256SUMS` detects download corruption. GitHub build provenance attached to the release provides a separate publisher-verification path. @@ -129,7 +159,8 @@ The helper path is a packaging contract. Until the helper is present, packages m ## Feature notes -- **ReFS:** Linux has no safe, production-quality ReFS formatter. ReFS creation is unavailable; existing ReFS media may be identified read-only. +- **ReFS:** Linux has no safe, production-quality ReFS formatter, and Windows allows ReFS creation only on Pro for Workstations, Enterprise, and Server through VDS. ReFS creation is unavailable on both; existing ReFS media may be identified read-only. +- **ext2/3/4 on Windows:** Windows has no ext formatter, so these file systems are offered only on Linux. - **MS-DOS:** Microsoft DOS system files are proprietary and are not distributed. A future workflow may accept user-supplied, lawfully obtained files. - **FFU:** Windows FFU capture/apply relies on Windows servicing components. It is not promised until a maintained, independently verifiable Linux implementation exists. - **Windows To Go:** Creation is recognized but blocked. A safe implementation @@ -143,6 +174,7 @@ The helper path is a packaging contract. Until the helper is present, packages m - [Safety and privilege model](docs/SAFETY.md) - [Architecture](docs/ARCHITECTURE.md) - [Building and packaging](docs/BUILDING.md) +- [Windows](docs/WINDOWS.md) ## License and attribution diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index 97f8908..30c2227 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -28,7 +28,7 @@ DiscUtils writer, pinned with dependency hashes and source provenance under ## Expected system dependencies -These tools and libraries are intended to remain system dependencies rather than copied into this repository: +These tools and libraries are intended to remain system dependencies on Linux rather than copied into this repository: | Component | Typical license | Purpose | |---|---|---| @@ -50,6 +50,24 @@ These tools and libraries are intended to remain system dependencies rather than License versions above are orientation only. The installed package's license metadata is authoritative. +## Windows build + +The Windows executable statically links these crates in addition to the +shared ones; their license texts ship with the crates: + +| Component | License | Purpose | +|---|---|---| +| windows-sys | MIT or Apache-2.0 | Win32 bindings | +| flate2 (miniz_oxide) | MIT or Apache-2.0 | gzip, zip deflate | +| bzip2 (libbz2-rs-sys) | MIT or Apache-2.0; bzip2-1.0.6 | bzip2 | +| lzma-rust2 | Apache-2.0 | xz, lzma | +| ruzstd | MIT | zstd | +| embed-resource (build only) | MIT | Icon and manifest resources | + +It calls, but never redistributes, Windows components: `fmifs.dll` +(`FormatEx`), `virtdisk.dll`, the storage and disk IOCTLs, the common file +dialog, and UAC. The Windows zip ships `LICENSE.txt` and this file. + ## Bundled boot assets - `crates/rufust-helper/assets/uefi-ntfs/`: the unchanged contents of upstream diff --git a/apps/rufust/Cargo.toml b/apps/rufust/Cargo.toml index 3242145..f4b7606 100644 --- a/apps/rufust/Cargo.toml +++ b/apps/rufust/Cargo.toml @@ -23,9 +23,31 @@ rufust-platform = { path = "../../crates/rufust-platform" } rufust-image = { path = "../../crates/rufust-image" } slint = { version = "=1.9.2", default-features = false, features = ["backend-winit", "renderer-femtovg", "std", "accessibility", "compat-1-2"] } i-slint-backend-winit = { version = "=1.9.2", default-features = false } +libc = "0.2" + +[target.'cfg(target_os = "linux")'.dependencies] ashpd = "=0.9.3" pollster = "=0.3.0" -libc = "0.2" + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.59", features = [ + "Win32_Foundation", + "Win32_Globalization", + "Win32_Security", + "Win32_Storage_FileSystem", + "Win32_System_Com", + "Win32_System_Pipes", + "Win32_System_Registry", + "Win32_System_Threading", + "Win32_System_Time", + "Win32_UI_Controls_Dialogs", + "Win32_UI_Input_KeyboardAndMouse", + "Win32_UI_Shell", + "Win32_UI_WindowsAndMessaging", +] } [build-dependencies] slint-build = "=1.9.2" + +[target.'cfg(windows)'.build-dependencies] +embed-resource = "3" diff --git a/apps/rufust/build.rs b/apps/rufust/build.rs index b9a4d30..5c6e53a 100644 --- a/apps/rufust/build.rs +++ b/apps/rufust/build.rs @@ -1,3 +1,90 @@ fn main() { slint_build::compile("ui/appwindow.slint").expect("Slint build failed"); + #[cfg(windows)] + windows_resources(); } + +/// Give `rufust.exe` the original Rufus icon and an `asInvoker` manifest: the +/// window runs unelevated and asks UAC only for its disk worker. +#[cfg(windows)] +fn windows_resources() { + use std::path::{Path, PathBuf}; + + let icons = Path::new("../../assets/icons"); + let out = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR")); + // An ICO whose entries are the original PNGs (supported since Vista). + let sizes = [16u32, 24, 32, 48, 64, 128, 256]; + let images = sizes + .iter() + .map(|size| { + let path = icons.join(format!("rufust-{size}.png")); + println!("cargo:rerun-if-changed={}", path.display()); + std::fs::read(&path).expect("icon PNG") + }) + .collect::>(); + let mut ico = Vec::new(); + ico.extend_from_slice(&[0, 0, 1, 0]); + ico.extend_from_slice(&(sizes.len() as u16).to_le_bytes()); + let mut offset = 6 + 16 * sizes.len() as u32; + for (size, image) in sizes.iter().zip(&images) { + let side = if *size >= 256 { 0 } else { *size as u8 }; + ico.extend_from_slice(&[side, side, 0, 0, 1, 0, 32, 0]); + ico.extend_from_slice(&(image.len() as u32).to_le_bytes()); + ico.extend_from_slice(&offset.to_le_bytes()); + offset += image.len() as u32; + } + for image in &images { + ico.extend_from_slice(image); + } + let icon = out.join("rufust.ico"); + std::fs::write(&icon, ico).expect("write icon"); + + let manifest = out.join("rufust.exe.manifest"); + std::fs::write(&manifest, MANIFEST).expect("write manifest"); + let quote = |path: &Path| path.display().to_string().replace('\\', "/"); + let script = out.join("rufust.rc"); + std::fs::write( + &script, + format!( + "1 ICON \"{}\"\n1 24 \"{}\"\n", + quote(&icon), + quote(&manifest) + ), + ) + .expect("write resource script"); + embed_resource::compile(&script, embed_resource::NONE) + .manifest_required() + .expect("compile Windows resources"); +} + +#[cfg(windows)] +const MANIFEST: &str = r#" + + + + + + + + + + + + + + + + + true/pm + PerMonitorV2 + true + + + + + + + + +"#; diff --git a/apps/rufust/src/desktop.rs b/apps/rufust/src/desktop.rs new file mode 100644 index 0000000..aeb3e95 --- /dev/null +++ b/apps/rufust/src/desktop.rs @@ -0,0 +1,141 @@ +//! Desktop integration that differs by platform: the image file chooser and +//! the system's light or dark preference. + +use std::path::PathBuf; + +/// File name patterns offered as "Disk images". +const IMAGE_PATTERNS: &[&str] = &[ + "*.iso", "*.img", "*.raw", "*.dmg", "*.vhd", "*.vhdx", "*.gz", "*.xz", "*.lzma", "*.bz2", + "*.zst", "*.zstd", "*.zip", "*.wim", "*.esd", "*.ffu", +]; + +/// Linux: the XDG desktop portal's file chooser. +#[cfg(target_os = "linux")] +pub fn pick_image_file() -> Result, String> { + use ashpd::desktop::file_chooser::{FileFilter, SelectedFiles}; + use ashpd::desktop::ResponseError; + + let images = IMAGE_PATTERNS + .iter() + .fold(FileFilter::new("Disk images"), |filter, pattern| { + filter.glob(pattern) + }); + + pollster::block_on(async { + let request = SelectedFiles::open_file() + .title("Select a disk image") + .accept_label("Select") + .modal(true) + .filter(images) + .filter(FileFilter::new("All files").glob("*")) + .send() + .await + .map_err(|error| format!("Could not open the system file chooser: {error}"))?; + + let selected = match request.response() { + Ok(selected) => selected, + Err(ashpd::Error::Response(ResponseError::Cancelled)) => return Ok(None), + Err(error) => return Err(format!("System file chooser failed: {error}")), + }; + selected + .uris() + .first() + .map(|uri| { + uri.to_file_path() + .map_err(|_| "The selected image is not a local file.".to_owned()) + }) + .transpose() + }) +} + +/// Linux: `GTK_THEME` names a dark variant. +#[cfg(target_os = "linux")] +pub fn prefers_dark() -> bool { + std::env::var("GTK_THEME") + .unwrap_or_default() + .to_ascii_lowercase() + .contains("dark") +} + +/// Windows: the common Open dialog, owned by (and modal to) the workbench. +#[cfg(windows)] +pub fn pick_image_file() -> Result, String> { + use std::ffi::OsString; + use std::os::windows::ffi::{OsStrExt, OsStringExt}; + use windows_sys::Win32::UI::Controls::Dialogs::{ + CommDlgExtendedError, GetOpenFileNameW, OFN_DONTADDTORECENT, OFN_EXPLORER, + OFN_FILEMUSTEXIST, OFN_HIDEREADONLY, OFN_NOCHANGEDIR, OFN_PATHMUSTEXIST, OPENFILENAMEW, + }; + use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetActiveWindow; + + let wide = |text: &str| std::ffi::OsStr::new(text).encode_wide().collect::>(); + // Pairs of NUL-terminated name and pattern, ending with an empty string. + let mut filter = Vec::new(); + filter.extend(wide("Disk images")); + filter.push(0); + filter.extend(wide(&IMAGE_PATTERNS.join(";"))); + filter.push(0); + filter.extend(wide("All files")); + filter.push(0); + filter.extend(wide("*.*")); + filter.extend([0, 0]); + let mut title = wide("Select a disk image"); + title.push(0); + let mut path = vec![0u16; 32_768]; + + // SAFETY: zero is a valid starting value for this plain structure. + let mut dialog: OPENFILENAMEW = unsafe { std::mem::zeroed() }; + dialog.lStructSize = size_of::() as u32; + // SAFETY: returns this thread's active window (the workbench) or null. + dialog.hwndOwner = unsafe { GetActiveWindow() }; + dialog.lpstrFilter = filter.as_ptr(); + dialog.nFilterIndex = 1; + dialog.lpstrFile = path.as_mut_ptr(); + dialog.nMaxFile = path.len() as u32; + dialog.lpstrTitle = title.as_ptr(); + dialog.Flags = OFN_EXPLORER + | OFN_FILEMUSTEXIST + | OFN_PATHMUSTEXIST + | OFN_HIDEREADONLY + | OFN_NOCHANGEDIR + | OFN_DONTADDTORECENT; + // SAFETY: every buffer outlives the modal call. + if unsafe { GetOpenFileNameW(&mut dialog) } == 0 { + // SAFETY: no arguments; zero means the user cancelled. + return match unsafe { CommDlgExtendedError() } { + 0 => Ok(None), + code => Err(format!("The file dialog failed (error 0x{code:x}).")), + }; + } + let end = path + .iter() + .position(|unit| *unit == 0) + .unwrap_or(path.len()); + Ok(Some(PathBuf::from(OsString::from_wide(&path[..end])))) +} + +/// Windows: the "Choose your app mode" setting. +#[cfg(windows)] +pub fn prefers_dark() -> bool { + use windows_sys::Win32::System::Registry::{RegGetValueW, HKEY_CURRENT_USER, RRF_RT_REG_DWORD}; + + let key: Vec = "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize\0" + .encode_utf16() + .collect(); + let value: Vec = "AppsUseLightTheme\0".encode_utf16().collect(); + let mut light = 1u32; + let mut size = size_of::() as u32; + // SAFETY: the strings are NUL-terminated and `light` holds one DWORD. + let status = unsafe { + RegGetValueW( + HKEY_CURRENT_USER, + key.as_ptr(), + value.as_ptr(), + RRF_RT_REG_DWORD, + std::ptr::null_mut(), + (&mut light as *mut u32).cast(), + &mut size, + ) + }; + status == 0 && light == 0 +} diff --git a/apps/rufust/src/helper_client.rs b/apps/rufust/src/helper_client.rs index ae1c7aa..0ecc325 100644 --- a/apps/rufust/src/helper_client.rs +++ b/apps/rufust/src/helper_client.rs @@ -1,39 +1,20 @@ -//! Starts disk operations through udisks2 (plug and play) or, where udisks2 -//! is missing, the short-lived, polkit-authorized native helper. +//! Starts disk operations outside the desktop's own privileges. +//! +//! Linux runs them through udisks2 or the polkit-authorized native helper; +//! Windows runs them in an elevated worker started through UAC. Either way the +//! window only builds a typed request and renders the events it gets back. -use std::fs; -use std::io::{BufRead, BufReader, Write}; -use std::os::unix::fs::{MetadataExt, PermissionsExt}; -use std::os::unix::process::CommandExt; -use std::path::Path; -use std::process::{Child, Command, Stdio}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{mpsc::Sender, Arc, Mutex}; +use rufust_helper_protocol::HelperEvent; -use rufust_core::progress::CancellationToken; -use rufust_helper::{execute_with_udisks, udisks_readiness, ExecutionOptions, HelperError}; -use rufust_helper_protocol::{decode_line, encode_line, HelperEvent, HelperRequest}; +#[cfg(target_os = "linux")] +mod linux; +#[cfg(windows)] +mod windows; -const PKEXEC: &str = "/usr/bin/pkexec"; -const PKACTION: &str = "/usr/bin/pkaction"; -const INSTALLED_HELPER: &str = "/usr/libexec/rufust-helper"; -const INSTALLED_POLICY: &str = "/usr/share/polkit-1/actions/io.github.nitrodiesel.rufust.policy"; -const ACTION_ID: &str = "io.github.nitrodiesel.rufust.helper"; -const MAX_POLICY_BYTES: u64 = 64 * 1024; -const APPIMAGE_ENVIRONMENT: [&str; 12] = [ - "APPDIR", - "APPIMAGE", - "ARGV0", - "GCONV_PATH", - "GI_TYPELIB_PATH", - "GTK_PATH", - "LD_AUDIT", - "LD_DEBUG", - "LD_LIBRARY_PATH", - "LD_PRELOAD", - "OWD", - "PYTHONPATH", -]; +#[cfg(target_os = "linux")] +pub use linux::{detect_backend, launch, RunningHelper}; +#[cfg(windows)] +pub use windows::{detect_backend, launch, RunningHelper, WORKER_FLAG}; #[derive(Debug)] pub enum WorkerMessage { @@ -47,358 +28,36 @@ pub enum WorkerMessage { pub enum Backend { /// The system udisks2 daemon, as the desktop user. Needs nothing /// installed, so the AppImage works on its own. + #[cfg_attr(windows, allow(dead_code))] Udisks { version: String }, /// The packaged root helper started through pkexec. + #[cfg_attr(windows, allow(dead_code))] NativeHelper, + /// Windows: an elevated copy of this program, approved through UAC for + /// each operation and driven over a private named pipe. + #[cfg_attr(not(windows), allow(dead_code))] + ElevatedWorker, } impl Backend { - /// Windows installer media is built through udisks2 only. + /// Windows installer media is built through udisks2 on Linux and by the + /// elevated worker on Windows; the native Linux helper cannot copy files. pub fn supports_file_copy(&self) -> bool { - matches!(self, Self::Udisks { .. }) + matches!(self, Self::Udisks { .. } | Self::ElevatedWorker) + } + + /// Whether the engine runs its own bad-block test instead of `badblocks`. + pub fn has_own_bad_block_test(&self) -> bool { + matches!(self, Self::Udisks { .. } | Self::ElevatedWorker) } pub fn describe(&self) -> String { match self { Self::Udisks { version } => format!("udisks2 {version}"), Self::NativeHelper => "the native privileged helper".into(), - } - } -} - -/// Prefer udisks2; fall back to the native helper where it is installed. -pub fn detect_backend() -> Result { - match udisks_readiness() { - Ok(version) => Ok(Backend::Udisks { version }), - Err(udisks_error) => helper_readiness() - .map(|()| Backend::NativeHelper) - .map_err(|_| { - format!( - "Writing needs the udisks2 disk service, which is not running ({udisks_error}). Install or start udisks2, or install the Rufust native package." - ) - }), - } -} - -pub struct RunningHelper { - child: Arc>>, - cancelled: Arc, - in_process: Option, -} - -impl RunningHelper { - pub fn cancel(&self) -> Result<(), String> { - self.cancelled.store(true, Ordering::Release); - if let Some(token) = &self.in_process { - token.request(); - return Ok(()); - } - let guard = self - .child - .lock() - .map_err(|_| "helper process lock was poisoned".to_owned())?; - if let Some(child) = guard.as_ref() { - request_termination(child) - .map_err(|error| format!("could not request helper cancellation: {error}"))?; - } - Ok(()) - } -} - -/// Run the request in this process, as the desktop user, through udisks2. -fn launch_udisks( - request: &HelperRequest, - sender: Sender, -) -> Result { - let cancel = CancellationToken::new(); - let options = ExecutionOptions { - dry_run: false, - cancel: cancel.clone(), - }; - let request = request.clone(); - let events = sender.clone(); - std::thread::Builder::new() - .name("udisks-job".into()) - .spawn(move || { - let sink = Box::new(move |event| { - let _ = events.send(WorkerMessage::Event(event)); - }); - let message = match execute_with_udisks(request, options, sink) { - Ok(_) => return, - Err(HelperError::Cancelled) => WorkerMessage::Cancelled, - Err(error) => WorkerMessage::Failed(error.to_string()), - }; - let _ = sender.send(message); - }) - .map_err(|error| format!("could not start the write job: {error}"))?; - Ok(RunningHelper { - child: Arc::new(Mutex::new(None)), - cancelled: Arc::new(AtomicBool::new(false)), - in_process: Some(cancel), - }) -} - -fn request_termination(child: &Child) -> std::io::Result<()> { - let pid = libc::pid_t::try_from(child.id()) - .map_err(|_| std::io::Error::other("helper pid was outside the platform range"))?; - if unsafe { libc::kill(-pid, libc::SIGTERM) } == 0 { - return Ok(()); - } - let error = std::io::Error::last_os_error(); - if error.raw_os_error() == Some(libc::ESRCH) { - Ok(()) - } else { - Err(error) - } -} - -fn isolate_process_group(command: &mut Command) { - // SAFETY: setpgid is async-signal-safe and no allocations occur after fork. - unsafe { - command.pre_exec(|| { - if libc::setpgid(0, 0) != 0 { - return Err(std::io::Error::last_os_error()); + Self::ElevatedWorker => { + "an elevated worker (Windows asks for administrator approval at Start)".into() } - Ok(()) - }); - } -} - -fn trusted_system_file(path: &str, executable: bool) -> Result { - let metadata = fs::metadata(path).map_err(|error| format!("{path} is unavailable: {error}"))?; - if !metadata.is_file() { - return Err(format!("{path} is not a regular file")); - } - if metadata.uid() != 0 || metadata.permissions().mode() & 0o022 != 0 { - return Err(format!( - "{path} must be owned by root and not writable by group or other users" - )); - } - if executable && metadata.permissions().mode() & 0o111 == 0 { - return Err(format!("{path} is not executable")); - } - Ok(metadata) -} - -fn helper_readiness() -> Result<(), String> { - if !Path::new(PKEXEC).is_file() || !Path::new(PKACTION).is_file() { - return Err( - "polkit is not installed; install pkexec and pkaction for authorized disk writes" - .into(), - ); - } - trusted_system_file(INSTALLED_HELPER, true)?; - let policy_metadata = trusted_system_file(INSTALLED_POLICY, false)?; - if policy_metadata.len() > MAX_POLICY_BYTES { - return Err(format!("{INSTALLED_POLICY} is unexpectedly large")); - } - let policy = fs::read_to_string(INSTALLED_POLICY) - .map_err(|error| format!("could not read {INSTALLED_POLICY}: {error}"))?; - if !policy_authorizes_helper(&policy) { - return Err("the installed polkit policy does not authorize the packaged helper".into()); - } - Ok(()) -} - -fn policy_authorizes_helper(policy: &str) -> bool { - policy.contains(&format!("")) - && policy.contains(&format!( - "{INSTALLED_HELPER}" - )) -} - -fn sanitize_appimage_environment(command: &mut Command) { - for variable in APPIMAGE_ENVIRONMENT { - command.env_remove(variable); - } -} - -fn installed_helper_is_compatible() -> Result<(), String> { - let mut command = Command::new(INSTALLED_HELPER); - command - .arg("--version") - .stdin(Stdio::null()) - .stderr(Stdio::null()); - sanitize_appimage_environment(&mut command); - let output = command - .output() - .map_err(|error| format!("could not query the privileged helper version: {error}"))?; - let expected = format!("rufust-helper {}", env!("CARGO_PKG_VERSION")); - if !output.status.success() || String::from_utf8_lossy(&output.stdout).trim() != expected { - return Err(format!( - "the installed privileged helper is incompatible; reinstall Rufust {}", - env!("CARGO_PKG_VERSION") - )); - } - Ok(()) -} - -fn registered_action_authorizes_helper() -> Result<(), String> { - let mut command = Command::new(PKACTION); - command - .args(["--verbose", "--action-id", ACTION_ID]) - .env("LC_ALL", "C"); - sanitize_appimage_environment(&mut command); - let output = command - .output() - .map_err(|error| format!("could not inspect the installed polkit action: {error}"))?; - if !output.status.success() { - return Err("the Rufust polkit action is not registered".into()); - } - let details = String::from_utf8_lossy(&output.stdout); - let expected = format!("org.freedesktop.policykit.exec.path -> {INSTALLED_HELPER}"); - if !details.contains(&expected) { - return Err("the registered polkit action does not target the packaged helper".into()); - } - Ok(()) -} - -pub fn launch( - backend: &Backend, - request: &HelperRequest, - sender: Sender, -) -> Result { - match backend { - Backend::Udisks { .. } => launch_udisks(request, sender), - Backend::NativeHelper => launch_native(request, sender), - } -} - -fn launch_native( - request: &HelperRequest, - sender: Sender, -) -> Result { - helper_readiness()?; - installed_helper_is_compatible()?; - registered_action_authorizes_helper()?; - - let mut command = Command::new(PKEXEC); - command - .arg(INSTALLED_HELPER) - .arg("--execute-json") - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); - sanitize_appimage_environment(&mut command); - isolate_process_group(&mut command); - let mut child = command - .spawn() - .map_err(|error| format!("could not request authorization: {error}"))?; - - let request_line = encode_line(request) - .map_err(|error| format!("could not encode helper request: {error}"))?; - let mut stdin = child - .stdin - .take() - .ok_or_else(|| "helper stdin was not available".to_owned())?; - stdin - .write_all(&request_line) - .map_err(|error| format!("could not send helper request: {error}"))?; - drop(stdin); - - let stdout = child - .stdout - .take() - .ok_or_else(|| "helper stdout was not available".to_owned())?; - let stderr = child - .stderr - .take() - .ok_or_else(|| "helper stderr was not available".to_owned())?; - let shared_child = Arc::new(Mutex::new(Some(child))); - let thread_child = Arc::clone(&shared_child); - let cancelled = Arc::new(AtomicBool::new(false)); - let thread_cancelled = Arc::clone(&cancelled); - - std::thread::spawn(move || { - let stderr_thread = std::thread::spawn(move || { - let mut lines = Vec::new(); - for line in BufReader::new(stderr).lines().map_while(Result::ok) { - if !line.trim().is_empty() { - lines.push(line); - } - } - lines.join("\n") - }); - - for line in BufReader::new(stdout).split(b'\n') { - let Ok(mut line) = line else { - break; - }; - if line.is_empty() { - continue; - } - line.push(b'\n'); - match decode_line::(&line) { - Ok(event) => { - if sender.send(WorkerMessage::Event(event)).is_err() { - return; - } - } - Err(error) => { - let _ = sender.send(WorkerMessage::Failed(format!( - "invalid response from privileged helper: {error}" - ))); - return; - } - } - } - - let status = thread_child - .lock() - .ok() - .and_then(|mut guard| guard.as_mut().and_then(|child| child.wait().ok())); - if let Ok(mut guard) = thread_child.lock() { - *guard = None; } - let stderr_text = stderr_thread.join().unwrap_or_default(); - - if thread_cancelled.load(Ordering::Acquire) { - let _ = sender.send(WorkerMessage::Cancelled); - } else if status.is_none_or(|status| !status.success()) { - let detail = if stderr_text.is_empty() { - "authorization was denied or the privileged helper failed".to_owned() - } else { - stderr_text - }; - let _ = sender.send(WorkerMessage::Failed(detail)); - } - }); - - Ok(RunningHelper { - child: shared_child, - cancelled, - in_process: None, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn cancellation_requests_sigterm_instead_of_forcing_sigkill() { - use std::os::unix::process::ExitStatusExt; - - let mut command = Command::new("/bin/sleep"); - command.arg("30"); - isolate_process_group(&mut command); - let mut child = command.spawn().expect("spawn sleep fixture"); - request_termination(&child).expect("send SIGTERM"); - let status = child.wait().expect("reap sleep fixture"); - assert_eq!(status.signal(), Some(libc::SIGTERM)); - } - - #[test] - fn policy_must_name_the_action_and_exact_helper_path() { - let valid = format!( - "{INSTALLED_HELPER}" - ); - assert!(policy_authorizes_helper(&valid)); - assert!(!policy_authorizes_helper( - &valid.replace(INSTALLED_HELPER, "/tmp/helper") - )); - assert!(!policy_authorizes_helper( - &valid.replace(ACTION_ID, "org.example.other") - )); } } diff --git a/apps/rufust/src/helper_client/linux.rs b/apps/rufust/src/helper_client/linux.rs new file mode 100644 index 0000000..b768661 --- /dev/null +++ b/apps/rufust/src/helper_client/linux.rs @@ -0,0 +1,376 @@ +//! Linux: disk operations run through udisks2 (plug and play) or, where +//! udisks2 is missing, the short-lived, polkit-authorized native helper. + +use std::fs; +use std::io::{BufRead, BufReader, Write}; +use std::os::unix::fs::{MetadataExt, PermissionsExt}; +use std::os::unix::process::CommandExt; +use std::path::Path; +use std::process::{Child, Command, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{mpsc::Sender, Arc, Mutex}; + +use rufust_core::progress::CancellationToken; +use rufust_helper::{execute_with_udisks, udisks_readiness, ExecutionOptions, HelperError}; +use rufust_helper_protocol::{decode_line, encode_line, HelperEvent, HelperRequest}; + +use super::{Backend, WorkerMessage}; + +const PKEXEC: &str = "/usr/bin/pkexec"; +const PKACTION: &str = "/usr/bin/pkaction"; +const INSTALLED_HELPER: &str = "/usr/libexec/rufust-helper"; +const INSTALLED_POLICY: &str = "/usr/share/polkit-1/actions/io.github.nitrodiesel.rufust.policy"; +const ACTION_ID: &str = "io.github.nitrodiesel.rufust.helper"; +const MAX_POLICY_BYTES: u64 = 64 * 1024; +const APPIMAGE_ENVIRONMENT: [&str; 12] = [ + "APPDIR", + "APPIMAGE", + "ARGV0", + "GCONV_PATH", + "GI_TYPELIB_PATH", + "GTK_PATH", + "LD_AUDIT", + "LD_DEBUG", + "LD_LIBRARY_PATH", + "LD_PRELOAD", + "OWD", + "PYTHONPATH", +]; + +/// Prefer udisks2; fall back to the native helper where it is installed. +pub fn detect_backend() -> Result { + match udisks_readiness() { + Ok(version) => Ok(Backend::Udisks { version }), + Err(udisks_error) => helper_readiness() + .map(|()| Backend::NativeHelper) + .map_err(|_| { + format!( + "Writing needs the udisks2 disk service, which is not running ({udisks_error}). Install or start udisks2, or install the Rufust native package." + ) + }), + } +} + +pub struct RunningHelper { + child: Arc>>, + cancelled: Arc, + in_process: Option, +} + +impl RunningHelper { + pub fn cancel(&self) -> Result<(), String> { + self.cancelled.store(true, Ordering::Release); + if let Some(token) = &self.in_process { + token.request(); + return Ok(()); + } + let guard = self + .child + .lock() + .map_err(|_| "helper process lock was poisoned".to_owned())?; + if let Some(child) = guard.as_ref() { + request_termination(child) + .map_err(|error| format!("could not request helper cancellation: {error}"))?; + } + Ok(()) + } +} + +/// Run the request in this process, as the desktop user, through udisks2. +fn launch_udisks( + request: &HelperRequest, + sender: Sender, +) -> Result { + let cancel = CancellationToken::new(); + let options = ExecutionOptions { + dry_run: false, + cancel: cancel.clone(), + }; + let request = request.clone(); + let events = sender.clone(); + std::thread::Builder::new() + .name("udisks-job".into()) + .spawn(move || { + let sink = Box::new(move |event| { + let _ = events.send(WorkerMessage::Event(event)); + }); + let message = match execute_with_udisks(request, options, sink) { + Ok(_) => return, + Err(HelperError::Cancelled) => WorkerMessage::Cancelled, + Err(error) => WorkerMessage::Failed(error.to_string()), + }; + let _ = sender.send(message); + }) + .map_err(|error| format!("could not start the write job: {error}"))?; + Ok(RunningHelper { + child: Arc::new(Mutex::new(None)), + cancelled: Arc::new(AtomicBool::new(false)), + in_process: Some(cancel), + }) +} + +fn request_termination(child: &Child) -> std::io::Result<()> { + let pid = libc::pid_t::try_from(child.id()) + .map_err(|_| std::io::Error::other("helper pid was outside the platform range"))?; + if unsafe { libc::kill(-pid, libc::SIGTERM) } == 0 { + return Ok(()); + } + let error = std::io::Error::last_os_error(); + if error.raw_os_error() == Some(libc::ESRCH) { + Ok(()) + } else { + Err(error) + } +} + +fn isolate_process_group(command: &mut Command) { + // SAFETY: setpgid is async-signal-safe and no allocations occur after fork. + unsafe { + command.pre_exec(|| { + if libc::setpgid(0, 0) != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } +} + +fn trusted_system_file(path: &str, executable: bool) -> Result { + let metadata = fs::metadata(path).map_err(|error| format!("{path} is unavailable: {error}"))?; + if !metadata.is_file() { + return Err(format!("{path} is not a regular file")); + } + if metadata.uid() != 0 || metadata.permissions().mode() & 0o022 != 0 { + return Err(format!( + "{path} must be owned by root and not writable by group or other users" + )); + } + if executable && metadata.permissions().mode() & 0o111 == 0 { + return Err(format!("{path} is not executable")); + } + Ok(metadata) +} + +fn helper_readiness() -> Result<(), String> { + if !Path::new(PKEXEC).is_file() || !Path::new(PKACTION).is_file() { + return Err( + "polkit is not installed; install pkexec and pkaction for authorized disk writes" + .into(), + ); + } + trusted_system_file(INSTALLED_HELPER, true)?; + let policy_metadata = trusted_system_file(INSTALLED_POLICY, false)?; + if policy_metadata.len() > MAX_POLICY_BYTES { + return Err(format!("{INSTALLED_POLICY} is unexpectedly large")); + } + let policy = fs::read_to_string(INSTALLED_POLICY) + .map_err(|error| format!("could not read {INSTALLED_POLICY}: {error}"))?; + if !policy_authorizes_helper(&policy) { + return Err("the installed polkit policy does not authorize the packaged helper".into()); + } + Ok(()) +} + +fn policy_authorizes_helper(policy: &str) -> bool { + policy.contains(&format!("")) + && policy.contains(&format!( + "{INSTALLED_HELPER}" + )) +} + +fn sanitize_appimage_environment(command: &mut Command) { + for variable in APPIMAGE_ENVIRONMENT { + command.env_remove(variable); + } +} + +fn installed_helper_is_compatible() -> Result<(), String> { + let mut command = Command::new(INSTALLED_HELPER); + command + .arg("--version") + .stdin(Stdio::null()) + .stderr(Stdio::null()); + sanitize_appimage_environment(&mut command); + let output = command + .output() + .map_err(|error| format!("could not query the privileged helper version: {error}"))?; + let expected = format!("rufust-helper {}", env!("CARGO_PKG_VERSION")); + if !output.status.success() || String::from_utf8_lossy(&output.stdout).trim() != expected { + return Err(format!( + "the installed privileged helper is incompatible; reinstall Rufust {}", + env!("CARGO_PKG_VERSION") + )); + } + Ok(()) +} + +fn registered_action_authorizes_helper() -> Result<(), String> { + let mut command = Command::new(PKACTION); + command + .args(["--verbose", "--action-id", ACTION_ID]) + .env("LC_ALL", "C"); + sanitize_appimage_environment(&mut command); + let output = command + .output() + .map_err(|error| format!("could not inspect the installed polkit action: {error}"))?; + if !output.status.success() { + return Err("the Rufust polkit action is not registered".into()); + } + let details = String::from_utf8_lossy(&output.stdout); + let expected = format!("org.freedesktop.policykit.exec.path -> {INSTALLED_HELPER}"); + if !details.contains(&expected) { + return Err("the registered polkit action does not target the packaged helper".into()); + } + Ok(()) +} + +pub fn launch( + backend: &Backend, + request: &HelperRequest, + sender: Sender, +) -> Result { + match backend { + Backend::Udisks { .. } => launch_udisks(request, sender), + Backend::NativeHelper => launch_native(request, sender), + Backend::ElevatedWorker => Err("the elevated worker is a Windows backend".into()), + } +} + +fn launch_native( + request: &HelperRequest, + sender: Sender, +) -> Result { + helper_readiness()?; + installed_helper_is_compatible()?; + registered_action_authorizes_helper()?; + + let mut command = Command::new(PKEXEC); + command + .arg(INSTALLED_HELPER) + .arg("--execute-json") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + sanitize_appimage_environment(&mut command); + isolate_process_group(&mut command); + let mut child = command + .spawn() + .map_err(|error| format!("could not request authorization: {error}"))?; + + let request_line = encode_line(request) + .map_err(|error| format!("could not encode helper request: {error}"))?; + let mut stdin = child + .stdin + .take() + .ok_or_else(|| "helper stdin was not available".to_owned())?; + stdin + .write_all(&request_line) + .map_err(|error| format!("could not send helper request: {error}"))?; + drop(stdin); + + let stdout = child + .stdout + .take() + .ok_or_else(|| "helper stdout was not available".to_owned())?; + let stderr = child + .stderr + .take() + .ok_or_else(|| "helper stderr was not available".to_owned())?; + let shared_child = Arc::new(Mutex::new(Some(child))); + let thread_child = Arc::clone(&shared_child); + let cancelled = Arc::new(AtomicBool::new(false)); + let thread_cancelled = Arc::clone(&cancelled); + + std::thread::spawn(move || { + let stderr_thread = std::thread::spawn(move || { + let mut lines = Vec::new(); + for line in BufReader::new(stderr).lines().map_while(Result::ok) { + if !line.trim().is_empty() { + lines.push(line); + } + } + lines.join("\n") + }); + + for line in BufReader::new(stdout).split(b'\n') { + let Ok(mut line) = line else { + break; + }; + if line.is_empty() { + continue; + } + line.push(b'\n'); + match decode_line::(&line) { + Ok(event) => { + if sender.send(WorkerMessage::Event(event)).is_err() { + return; + } + } + Err(error) => { + let _ = sender.send(WorkerMessage::Failed(format!( + "invalid response from privileged helper: {error}" + ))); + return; + } + } + } + + let status = thread_child + .lock() + .ok() + .and_then(|mut guard| guard.as_mut().and_then(|child| child.wait().ok())); + if let Ok(mut guard) = thread_child.lock() { + *guard = None; + } + let stderr_text = stderr_thread.join().unwrap_or_default(); + + if thread_cancelled.load(Ordering::Acquire) { + let _ = sender.send(WorkerMessage::Cancelled); + } else if status.is_none_or(|status| !status.success()) { + let detail = if stderr_text.is_empty() { + "authorization was denied or the privileged helper failed".to_owned() + } else { + stderr_text + }; + let _ = sender.send(WorkerMessage::Failed(detail)); + } + }); + + Ok(RunningHelper { + child: shared_child, + cancelled, + in_process: None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cancellation_requests_sigterm_instead_of_forcing_sigkill() { + use std::os::unix::process::ExitStatusExt; + + let mut command = Command::new("/bin/sleep"); + command.arg("30"); + isolate_process_group(&mut command); + let mut child = command.spawn().expect("spawn sleep fixture"); + request_termination(&child).expect("send SIGTERM"); + let status = child.wait().expect("reap sleep fixture"); + assert_eq!(status.signal(), Some(libc::SIGTERM)); + } + + #[test] + fn policy_must_name_the_action_and_exact_helper_path() { + let valid = format!( + "{INSTALLED_HELPER}" + ); + assert!(policy_authorizes_helper(&valid)); + assert!(!policy_authorizes_helper( + &valid.replace(INSTALLED_HELPER, "/tmp/helper") + )); + assert!(!policy_authorizes_helper( + &valid.replace(ACTION_ID, "org.example.other") + )); + } +} diff --git a/apps/rufust/src/helper_client/windows.rs b/apps/rufust/src/helper_client/windows.rs new file mode 100644 index 0000000..8fb73c5 --- /dev/null +++ b/apps/rufust/src/helper_client/windows.rs @@ -0,0 +1,486 @@ +//! Windows: each operation runs in an elevated copy of this program. +//! +//! The window creates two single-instance, local-only pipes, starts +//! `rufust.exe --elevated-worker ` with the `runas` verb (one UAC +//! prompt), and accepts the pipe clients only if they are that process. The +//! request goes out on `-control`, events come back on `-events`, +//! and a `cancel` line (or closing the control pipe) requests cancellation. + +use std::fs::File; +use std::io::{BufRead, BufReader, Write}; +use std::os::windows::ffi::OsStrExt; +use std::os::windows::io::{AsRawHandle, FromRawHandle, RawHandle}; +use std::ptr; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{mpsc::Sender, Arc, Mutex}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use rufust_helper_protocol::{decode_line, encode_line, HelperEvent, HelperRequest}; +use windows_sys::Win32::Foundation::{ + CloseHandle, GetLastError, ERROR_CANCELLED, ERROR_PIPE_CONNECTED, HANDLE, HWND, + INVALID_HANDLE_VALUE, +}; +use windows_sys::Win32::Storage::FileSystem::{ + CreateFileW, FILE_FLAG_FIRST_PIPE_INSTANCE, FILE_GENERIC_READ, FILE_GENERIC_WRITE, + OPEN_EXISTING, PIPE_ACCESS_INBOUND, PIPE_ACCESS_OUTBOUND, +}; +use windows_sys::Win32::System::Com::{ + CoInitializeEx, COINIT_APARTMENTTHREADED, COINIT_DISABLE_OLE1DDE, +}; +use windows_sys::Win32::System::Pipes::{ + ConnectNamedPipe, CreateNamedPipeW, GetNamedPipeClientProcessId, PIPE_READMODE_BYTE, + PIPE_REJECT_REMOTE_CLIENTS, PIPE_TYPE_BYTE, PIPE_WAIT, +}; +use windows_sys::Win32::System::Threading::{ + GetExitCodeProcess, GetProcessId, WaitForSingleObject, INFINITE, +}; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetActiveWindow; +use windows_sys::Win32::UI::Shell::{ + ShellExecuteExW, SEE_MASK_FLAG_NO_UI, SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS, + SHELLEXECUTEINFOW, +}; +use windows_sys::Win32::UI::WindowsAndMessaging::SW_HIDE; + +use super::{Backend, WorkerMessage}; + +/// The argument that turns this program into the elevated worker. +pub const WORKER_FLAG: &str = "--elevated-worker"; +const PIPE_BUFFER: u32 = 64 * 1024; + +fn wide(value: impl AsRef) -> Vec { + value.as_ref().encode_wide().chain(Some(0)).collect() +} + +/// UAC asks at Start, so writing is always offered on Windows. +pub fn detect_backend() -> Result { + Ok(Backend::ElevatedWorker) +} + +pub struct RunningHelper { + control: Arc>>, + cancelled: Arc, +} + +impl RunningHelper { + pub fn cancel(&self) -> Result<(), String> { + self.cancelled.store(true, Ordering::Release); + let mut guard = self + .control + .lock() + .map_err(|_| "worker pipe lock was poisoned".to_owned())?; + if let Some(control) = guard.as_mut() { + // A worker that already finished has closed its end; that is fine. + let _ = control.write_all(b"cancel\n"); + let _ = control.flush(); + } + Ok(()) + } +} + +/// A process handle shared with the watchdog thread. +struct Process(HANDLE); + +// SAFETY: process handles may be waited on from any thread. +unsafe impl Send for Process {} +unsafe impl Sync for Process {} + +impl Drop for Process { + fn drop(&mut self) { + // SAFETY: owned handle, closed once. + unsafe { CloseHandle(self.0) }; + } +} + +impl Process { + fn wait(&self) -> u32 { + let mut code = 1u32; + // SAFETY: the handle is live for the life of `self`. + unsafe { + WaitForSingleObject(self.0, INFINITE); + GetExitCodeProcess(self.0, &mut code); + } + code + } + + fn id(&self) -> u32 { + // SAFETY: the handle is live for the life of `self`. + unsafe { GetProcessId(self.0) } + } +} + +fn create_pipe(name: &str, inbound: bool) -> Result { + let path = wide(name); + // SAFETY: the name is NUL-terminated; default security limits the pipe + // to this user, SYSTEM, and administrators. + let handle = unsafe { + CreateNamedPipeW( + path.as_ptr(), + (if inbound { + PIPE_ACCESS_INBOUND + } else { + PIPE_ACCESS_OUTBOUND + }) | FILE_FLAG_FIRST_PIPE_INSTANCE, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, + 1, + PIPE_BUFFER, + PIPE_BUFFER, + 0, + ptr::null(), + ) + }; + if handle == INVALID_HANDLE_VALUE { + return Err(format!( + "could not create the worker pipe: {}", + std::io::Error::last_os_error() + )); + } + // SAFETY: the new handle is owned by the returned File. + Ok(unsafe { File::from_raw_handle(handle as RawHandle) }) +} + +/// Wait for the client and confirm it is the worker we started. +fn accept(pipe: &File, worker: u32) -> Result<(), String> { + let handle = pipe.as_raw_handle(); + // SAFETY: a live pipe handle; a synchronous connect. + if unsafe { ConnectNamedPipe(handle, ptr::null_mut()) } == 0 + // SAFETY: reads this thread's last error. + && unsafe { GetLastError() } != ERROR_PIPE_CONNECTED + { + return Err(format!( + "the worker did not connect: {}", + std::io::Error::last_os_error() + )); + } + let mut client = 0u32; + // SAFETY: writes one u32. + if unsafe { GetNamedPipeClientProcessId(handle, &mut client) } == 0 || client != worker { + return Err("the worker exited before it connected".into()); + } + Ok(()) +} + +/// Unblock a pending connect after the worker died without connecting. +fn poke(name: &str, write: bool) { + let path = wide(name); + // SAFETY: the name is NUL-terminated; the handle is closed at once. + let handle = unsafe { + CreateFileW( + path.as_ptr(), + if write { + FILE_GENERIC_WRITE + } else { + FILE_GENERIC_READ + }, + 0, + ptr::null(), + OPEN_EXISTING, + 0, + ptr::null_mut(), + ) + }; + if handle != INVALID_HANDLE_VALUE { + // SAFETY: closes the handle opened above. + unsafe { CloseHandle(handle) }; + } +} + +/// Start the elevated worker; `Ok(None)` when the user declines UAC. +fn elevate(owner: HWND, pipe: &str) -> Result, String> { + let exe = std::env::current_exe() + .map_err(|error| format!("could not locate this program: {error}"))?; + let file = wide(&exe); + let verb = wide("runas"); + let parameters = wide(format!("{WORKER_FLAG} {pipe}")); + let directory = exe.parent().map(wide); + // SAFETY: initializes COM for ShellExecuteEx on this worker thread. + unsafe { + CoInitializeEx( + ptr::null(), + (COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE) as u32, + ) + }; + // SAFETY: zero is a valid starting value for this plain structure. + let mut info: SHELLEXECUTEINFOW = unsafe { std::mem::zeroed() }; + info.cbSize = size_of::() as u32; + info.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI; + info.hwnd = owner; + info.lpVerb = verb.as_ptr(); + info.lpFile = file.as_ptr(); + info.lpParameters = parameters.as_ptr(); + info.lpDirectory = directory.as_ref().map_or(ptr::null(), |d| d.as_ptr()); + info.nShow = SW_HIDE; + // SAFETY: every string outlives the call. + if unsafe { ShellExecuteExW(&mut info) } == 0 { + // SAFETY: reads this thread's last error. + if unsafe { GetLastError() } == ERROR_CANCELLED { + return Ok(None); + } + return Err(format!( + "could not start the elevated worker: {}", + std::io::Error::last_os_error() + )); + } + if info.hProcess.is_null() { + return Err("Windows did not report the elevated worker process".into()); + } + Ok(Some(Process(info.hProcess))) +} + +pub fn launch( + backend: &Backend, + request: &HelperRequest, + sender: Sender, +) -> Result { + if *backend != Backend::ElevatedWorker { + return Err("only the elevated worker runs disk operations on Windows".into()); + } + // SAFETY: returns this thread's active window, the workbench, or null. + let owner = unsafe { GetActiveWindow() } as isize; + start(request, sender, move |name| elevate(owner as HWND, name)) +} + +/// Create the pipes, start the worker with `spawn(pipe name)`, and relay its +/// events. `spawn` returns `None` when the user declines. +fn start( + request: &HelperRequest, + sender: Sender, + spawn: impl FnOnce(&str) -> Result, String> + Send + 'static, +) -> Result { + let nonce = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_nanos()); + let name = format!("rufust-{}-{nonce}", std::process::id()); + let control_name = format!(r"\\.\pipe\{name}-control"); + let events_name = format!(r"\\.\pipe\{name}-events"); + let control = create_pipe(&control_name, false)?; + let events = create_pipe(&events_name, true)?; + let request_line = + encode_line(request).map_err(|error| format!("could not encode the request: {error}"))?; + // The pipe joins the shared slot only once the request is out, so a + // cancel click never waits on the connection. + let slot = Arc::new(Mutex::new(None::)); + let cancelled = Arc::new(AtomicBool::new(false)); + let thread_control = Arc::clone(&slot); + let thread_cancelled = Arc::clone(&cancelled); + std::thread::Builder::new() + .name("elevated-worker".into()) + .spawn(move || { + let fail = |message: String| { + let _ = sender.send(WorkerMessage::Failed(message)); + }; + let process = match spawn(&name) { + Ok(Some(process)) => Arc::new(process), + Ok(None) => { + return fail("Administrator approval was declined; nothing was written.".into()) + } + Err(error) => return fail(error), + }; + let worker = process.id(); + let watchdog = Arc::clone(&process); + let (control_name, events_name) = (control_name.clone(), events_name.clone()); + std::thread::spawn(move || { + watchdog.wait(); + poke(&control_name, false); + poke(&events_name, true); + }); + + let mut control = control; + let connected = accept(&control, worker) + .and_then(|()| accept(&events, worker)) + .and_then(|()| { + control + .write_all(&request_line) + .and_then(|()| control.flush()) + .map_err(|error| format!("could not send the request: {error}")) + }); + if let Ok(mut guard) = thread_control.lock() { + // `cancel` sets the flag before it takes this lock. + if thread_cancelled.load(Ordering::Acquire) { + let _ = control.write_all(b"cancel\n"); + } + *guard = Some(control); + } + if let Err(error) = connected { + let code = process.wait(); + return fail(format!("{error} (exit code {code})")); + } + + let mut finished = false; + for line in BufReader::new(events).split(b'\n') { + let Ok(mut line) = line else { + break; + }; + if line.is_empty() { + continue; + } + line.push(b'\n'); + match decode_line::(&line) { + Ok(event) => { + finished |= matches!(event, HelperEvent::Finished { .. }); + if sender.send(WorkerMessage::Event(event)).is_err() { + break; + } + } + Err(error) => { + return fail(format!( + "invalid response from the elevated worker: {error}" + )) + } + } + } + let code = process.wait(); + if let Ok(mut guard) = thread_control.lock() { + *guard = None; + } + if finished { + return; + } + if thread_cancelled.load(Ordering::Acquire) { + let _ = sender.send(WorkerMessage::Cancelled); + } else { + fail(format!( + "the elevated worker stopped without a result (exit code {code})" + )); + } + }) + .map_err(|error| format!("could not start the write job: {error}"))?; + + Ok(RunningHelper { + control: slot, + cancelled, + }) +} + +/// The worker protocol, end to end, against `rufust-helper.exe --execute-pipe` +/// on a disposable virtual disk. `scripts/windows/vhd-tests.ps1` runs these +/// elevated with `RUFUST_TEST_DISK` set; any other disk is refused. +#[cfg(test)] +mod tests { + use super::*; + use std::os::windows::io::IntoRawHandle; + use std::sync::mpsc; + use std::time::Duration; + + use rufust_core::plan::{BootMode, FileSystem, PartitionScheme}; + use rufust_core::progress::{JobId, ProgressStage}; + use rufust_helper_protocol::{ + FormatSpec, HelperOperation, HelperResult, TargetIdentity, PROTOCOL_VERSION, + }; + use rufust_platform::windows as platform; + + fn format_request(bad_blocks: bool) -> Option { + let number: u32 = std::env::var("RUFUST_TEST_DISK").ok()?.parse().ok()?; + let identity = rufust_platform::discover_devices(true) + .expect("discovery") + .into_iter() + .find(|device| device.minor == number) + .expect("the disk is attached"); + assert_eq!(identity.transport, "loop", "refusing a non-virtual disk"); + let block = platform::to_block_device(&identity, &platform::volumes()); + Some(HelperRequest { + protocol_version: PROTOCOL_VERSION, + job_id: JobId::new(7), + target: TargetIdentity { + node: identity.node.clone(), + fingerprint: block.fingerprint, + display_name: identity.display_name(), + model: identity.model.clone(), + serial: identity.serial.clone(), + }, + operation: HelperOperation::FormatMedia { + format: FormatSpec { + scheme: PartitionScheme::Gpt, + boot_mode: BootMode::NonBootable, + filesystem: FileSystem::Ntfs, + label: "PIPE TEST".into(), + cluster_size: None, + persistence_bytes: 0, + quick_format: true, + }, + bad_blocks, + }, + action_name: "test".into(), + }) + } + + fn helper_spawner() -> impl FnOnce(&str) -> Result, String> + Send { + |name: &str| { + // target\debug\deps\rufust-*.exe -> target\debug\rufust-helper.exe + let exe = std::env::current_exe().map_err(|error| error.to_string())?; + let helper = exe + .parent() + .and_then(|deps| deps.parent()) + .map(|debug| debug.join("rufust-helper.exe")) + .filter(|helper| helper.is_file()) + .ok_or("build rufust-helper first")?; + let child = std::process::Command::new(helper) + .args(["--execute-pipe", name]) + .spawn() + .map_err(|error| error.to_string())?; + Ok(Some(Process(child.into_raw_handle() as HANDLE))) + } + } + + fn finish(receiver: &mpsc::Receiver) -> Result { + loop { + match receiver.recv_timeout(Duration::from_secs(300)) { + Ok(WorkerMessage::Event(HelperEvent::Finished { result, .. })) => { + return Ok(result) + } + Ok(WorkerMessage::Event(_)) => {} + Ok(WorkerMessage::Failed(error)) => return Err(error), + Ok(WorkerMessage::Cancelled) => return Err("cancelled without a result".into()), + Err(error) => return Err(error.to_string()), + } + } + } + + #[test] + #[ignore = "needs an elevated shell, rufust-helper.exe, and RUFUST_TEST_DISK"] + fn worker_formats_through_the_pipes() { + let Some(request) = format_request(false) else { + return; + }; + let (sender, receiver) = mpsc::channel(); + let _running = start(&request, sender, helper_spawner()).expect("start"); + assert_eq!(finish(&receiver), Ok(HelperResult::Success)); + } + + #[test] + #[ignore = "needs an elevated shell, rufust-helper.exe, and RUFUST_TEST_DISK"] + fn cancel_reaches_the_worker() { + let Some(request) = format_request(true) else { + return; + }; + let (sender, receiver) = mpsc::channel(); + let running = start(&request, sender, helper_spawner()).expect("start"); + // Cancel once the long bad-block pass is under way. + loop { + match receiver.recv_timeout(Duration::from_secs(120)) { + Ok(WorkerMessage::Event(HelperEvent::Progress { + stage: ProgressStage::TestingMedia, + .. + })) => break, + Ok(WorkerMessage::Event(_)) => {} + other => panic!("unexpected before the bad-block test: {other:?}"), + } + } + running.cancel().expect("cancel"); + assert!(matches!( + finish(&receiver), + Ok(HelperResult::Cancelled { .. }) + )); + } + + #[test] + fn a_declined_prompt_writes_nothing() { + let request = + rufust_helper::sample_dry_request(std::path::PathBuf::from(r"\.\PhysicalDrive9")); + let (sender, receiver) = mpsc::channel(); + let _running = start(&request, sender, |_: &str| Ok(None)).expect("start"); + match receiver.recv_timeout(Duration::from_secs(10)) { + Ok(WorkerMessage::Failed(message)) => assert!(message.contains("declined")), + other => panic!("expected a declined failure, got {other:?}"), + } + } +} diff --git a/apps/rufust/src/hotplug.rs b/apps/rufust/src/hotplug.rs index 56e833d..5fd1069 100644 --- a/apps/rufust/src/hotplug.rs +++ b/apps/rufust/src/hotplug.rs @@ -1,8 +1,9 @@ //! Lightweight block-device change detection for the desktop application. //! //! Linux updates `/sys/class/block` as disks and their partitions appear or -//! disappear. Polling that small directory avoids a daemon dependency and a -//! one-slot channel naturally coalesces bursts of kernel events. +//! disappear; Windows lists disk interfaces and volumes. Polling that small +//! snapshot avoids a daemon dependency and a one-slot channel naturally +//! coalesces bursts of device events. use std::ffi::OsString; use std::fs; @@ -13,6 +14,7 @@ use std::sync::{Arc, Condvar, Mutex}; use std::thread::{self, JoinHandle}; use std::time::Duration; +#[cfg(not(windows))] const SYS_BLOCK: &str = "/sys/class/block"; const SCAN_INTERVAL: Duration = Duration::from_millis(500); @@ -23,18 +25,37 @@ pub struct BlockDeviceWatcher { } impl BlockDeviceWatcher { + #[cfg(not(windows))] pub fn spawn(changes: SyncSender<()>) -> io::Result { Self::spawn_at(PathBuf::from(SYS_BLOCK), SCAN_INTERVAL, changes) } + #[cfg(windows)] + pub fn spawn(changes: SyncSender<()>) -> io::Result { + Self::spawn_with( + rufust_platform::windows::device_snapshot, + SCAN_INTERVAL, + changes, + ) + } + + #[cfg_attr(windows, allow(dead_code))] fn spawn_at( sys_block: PathBuf, scan_interval: Duration, changes: SyncSender<()>, + ) -> io::Result { + Self::spawn_with(move || block_names(&sys_block), scan_interval, changes) + } + + fn spawn_with( + snapshot: impl Fn() -> io::Result> + Send + 'static, + scan_interval: Duration, + changes: SyncSender<()>, ) -> io::Result { // Establish the baseline before returning so a device connected just // after startup cannot race with worker initialization. - let mut previous = block_names(&sys_block)?; + let mut previous = snapshot()?; let stop = Arc::new((Mutex::new(false), Condvar::new())); let worker_stop = Arc::clone(&stop); let worker = thread::Builder::new() @@ -50,8 +71,8 @@ impl BlockDeviceWatcher { } drop(guard); - let Ok(current) = block_names(&sys_block) else { - // A transient sysfs read failure is not a device removal. + let Ok(current) = snapshot() else { + // A transient read failure is not a device removal. continue; }; if current == previous { @@ -84,6 +105,7 @@ impl Drop for BlockDeviceWatcher { } } +#[cfg_attr(windows, allow(dead_code))] fn block_names(sys_block: &Path) -> io::Result> { let mut names = fs::read_dir(sys_block)? .filter_map(|entry| entry.ok().map(|entry| entry.file_name())) diff --git a/apps/rufust/src/image_inspection.rs b/apps/rufust/src/image_inspection.rs index 67b81fe..6fe0e12 100644 --- a/apps/rufust/src/image_inspection.rs +++ b/apps/rufust/src/image_inspection.rs @@ -1,7 +1,6 @@ //! Read-only background inspection; write authorization remains in the helper. use std::fs::OpenOptions; -use std::os::unix::fs::OpenOptionsExt; use std::path::Path; use rufust_core::plan::ImageSourceKind; @@ -10,10 +9,34 @@ use rufust_image::{ImageError, ImageReport}; pub fn inspect(path: &Path, cancel: &CancellationToken) -> Result { check_cancel(cancel)?; - let mut file = OpenOptions::new() - .read(true) - .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC) - .open(path)?; + let mut options = OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC); + } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + use windows_sys::Win32::Storage::FileSystem::{ + FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, + }; + // Open a link itself rather than its target, then refuse it below; + // backup semantics lets a directory open so it is reported as such. + options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS); + } + let mut file = options.open(path)?; + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + let attributes = file.metadata()?.file_attributes(); + if attributes & windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT != 0 { + return Err(ImageError::Unsupported( + "links are not accepted; select the image file itself".into(), + )); + } + } let mut report = rufust_image::analyze_file(path, &mut file)?; check_cancel(cancel)?; if matches!(report.kind, ImageSourceKind::Vhd | ImageSourceKind::Vhdx) { @@ -74,9 +97,12 @@ mod tests { let report = inspect(&source, &cancel).expect("raw preview"); assert_eq!(report.kind, ImageSourceKind::Raw); assert_eq!(report.size_bytes, 4096); - let link = fixture.0.join("link.img"); - std::os::unix::fs::symlink(&source, &link).expect("symlink fixture"); - assert!(inspect(&link, &cancel).is_err()); + #[cfg(unix)] + { + let link = fixture.0.join("link.img"); + std::os::unix::fs::symlink(&source, &link).expect("symlink fixture"); + assert!(inspect(&link, &cancel).is_err()); + } assert!(matches!( inspect(&fixture.0, &cancel), Err(ImageError::NotAFile(_)) @@ -89,6 +115,7 @@ mod tests { } #[test] + #[cfg(target_os = "linux")] #[ignore = "requires non-root user, qemu-img, qemu-nbd and nbdinfo"] fn desktop_virtual_preview_reports_capacity_without_changing_source() { assert_ne!( @@ -120,3 +147,22 @@ mod tests { } } } + +#[cfg(all(test, windows))] +mod windows_tests { + use super::*; + + /// Run unelevated (for example under `runas /trustlevel:0x20000`) with + /// `RUFUST_TEST_VHD_SOURCE` naming a VHD or VHDX. + #[test] + #[ignore = "needs RUFUST_TEST_VHD_SOURCE"] + fn virtual_disk_preview_reports_capacity() { + let Some(source) = std::env::var_os("RUFUST_TEST_VHD_SOURCE") else { + return; + }; + let report = inspect(std::path::Path::new(&source), &CancellationToken::new()) + .expect("virtual preview"); + let expanded = report.decompressed_size_bytes.expect("inspected disk size"); + assert!(expanded >= 16 * 1024 * 1024 && expanded % 512 == 0); + } +} diff --git a/apps/rufust/src/main.rs b/apps/rufust/src/main.rs index 5bd5018..d143bc5 100644 --- a/apps/rufust/src/main.rs +++ b/apps/rufust/src/main.rs @@ -1,6 +1,11 @@ //! Rufust desktop — presentation only; destructive I/O stays in the helper. +//! +//! On Windows the same program, started elevated with `--elevated-worker`, +//! is that helper: it serves one request over the window's private pipes. +#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")] mod confirmation; +mod desktop; mod helper_client; mod hotplug; mod image_inspection; @@ -15,8 +20,6 @@ use std::rc::Rc; use std::sync::mpsc; use std::time::Duration; -use ashpd::desktop::file_chooser::{FileFilter, SelectedFiles}; -use ashpd::desktop::ResponseError; use helper_client::{RunningHelper, WorkerMessage}; use hotplug::BlockDeviceWatcher; use rufust_helper_protocol::{HelperEvent, HelperResult}; @@ -33,6 +36,13 @@ mod generated_ui { use generated_ui::*; fn main() -> Result<(), Box> { + #[cfg(windows)] + { + let arguments = std::env::args().collect::>(); + if arguments.len() == 3 && arguments[1] == helper_client::WORKER_FLAG { + std::process::exit(i32::from(rufust_helper::serve_pipe(&arguments[2]))); + } + } if std::env::args_os().len() == 2 && std::env::args_os() .nth(1) @@ -125,11 +135,15 @@ fn main() -> Result<(), Box> { .collect::>(), ))); ui.set_app_version(env!("CARGO_PKG_VERSION").into()); - let desktop_theme = std::env::var("GTK_THEME").unwrap_or_default(); + if cfg!(windows) { + ui.set_privilege_note( + "Destructive writes run in a separate worker that Windows elevates only after you approve it. The window itself never runs as administrator.".into(), + ); + } ui.set_dark_mode( std::env::var("RUFUST_THEME") .map(|value| !value.eq_ignore_ascii_case("light")) - .unwrap_or_else(|_| desktop_theme.to_ascii_lowercase().contains("dark")), + .unwrap_or_else(|_| desktop::prefers_dark()), ); refresh_filesystems(&ui, &state.borrow()); @@ -310,7 +324,7 @@ fn main() -> Result<(), Box> { if state.borrow().is_busy || state.borrow().image_inspecting { return; } - match pick_image_file() { + match desktop::pick_image_file() { Ok(Some(path)) => { let mut st = state.borrow_mut(); let Some((generation, cancel)) = st.begin_image_inspection(path.clone()) @@ -867,52 +881,6 @@ fn string_model(items: &[&str]) -> ModelRc { ModelRc::new(VecModel::from(v)) } -fn pick_image_file() -> Result, String> { - let images = FileFilter::new("Disk images") - .glob("*.iso") - .glob("*.img") - .glob("*.raw") - .glob("*.dmg") - .glob("*.vhd") - .glob("*.vhdx") - .glob("*.gz") - .glob("*.xz") - .glob("*.lzma") - .glob("*.bz2") - .glob("*.zst") - .glob("*.zstd") - .glob("*.zip") - .glob("*.wim") - .glob("*.esd") - .glob("*.ffu"); - - pollster::block_on(async { - let request = SelectedFiles::open_file() - .title("Select a disk image") - .accept_label("Select") - .modal(true) - .filter(images) - .filter(FileFilter::new("All files").glob("*")) - .send() - .await - .map_err(|error| format!("Could not open the system file chooser: {error}"))?; - - let selected = match request.response() { - Ok(selected) => selected, - Err(ashpd::Error::Response(ResponseError::Cancelled)) => return Ok(None), - Err(error) => return Err(format!("System file chooser failed: {error}")), - }; - selected - .uris() - .first() - .map(|uri| { - uri.to_file_path() - .map_err(|_| "The selected image is not a local file.".to_owned()) - }) - .transpose() - }) -} - fn refresh_filesystems(ui: &AppWindow, state: &AppState) { let labels: Vec = state .available_filesystems() diff --git a/apps/rufust/src/regional.rs b/apps/rufust/src/regional.rs index aa69a30..0396c78 100644 --- a/apps/rufust/src/regional.rs +++ b/apps/rufust/src/regional.rs @@ -1,6 +1,9 @@ //! "Set regional options to the same values as this user's": the Linux //! locale, keyboard layout, and time zone in Windows' answer-file notation. -//! Upstream reads the same values from the Windows registry and NLS APIs. +//! Upstream reads the same values from the Windows registry and NLS APIs, +//! and so does the Windows build. +// The Linux readers stay compiled (and tested) on Windows. +#![cfg_attr(windows, allow(dead_code))] use std::path::Path; @@ -67,6 +70,80 @@ const KEYBOARDS: &[(&str, &str)] = &[ /// This session's regional settings, matched against the image's languages /// so that Windows is never asked for a display language it does not have. +/// Windows reports them directly, as upstream reads them. +#[cfg(windows)] +pub fn current(image_languages: &[String]) -> RegionalSettings { + use windows_sys::Win32::Globalization::{ + GetSystemDefaultLocaleName, GetUserDefaultLocaleName, GetUserDefaultUILanguage, + LCIDToLocaleName, + }; + use windows_sys::Win32::System::Time::{ + GetDynamicTimeZoneInformation, DYNAMIC_TIME_ZONE_INFORMATION, TIME_ZONE_ID_INVALID, + }; + use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetKeyboardLayoutNameW; + + const LOCALE_NAME_MAX_LENGTH: usize = 85; + let text = |buffer: &[u16]| { + let end = buffer.iter().position(|c| *c == 0).unwrap_or(buffer.len()); + String::from_utf16_lossy(&buffer[..end]) + }; + let locale = |read: unsafe extern "system" fn(*mut u16, i32) -> i32| { + let mut buffer = [0u16; LOCALE_NAME_MAX_LENGTH]; + // SAFETY: the buffer holds LOCALE_NAME_MAX_LENGTH characters. + let length = unsafe { read(buffer.as_mut_ptr(), buffer.len() as i32) }; + Some(text(&buffer)) + .filter(|name| length > 0 && !name.is_empty()) + .unwrap_or_else(|| "en-US".into()) + }; + let system_locale = locale(GetSystemDefaultLocaleName); + let user_locale = locale(GetUserDefaultLocaleName); + + let mut buffer = [0u16; LOCALE_NAME_MAX_LENGTH]; + // SAFETY: a LANGID is a valid LCID with the default sort; the buffer + // holds LOCALE_NAME_MAX_LENGTH characters. + let length = unsafe { + LCIDToLocaleName( + u32::from(GetUserDefaultUILanguage()), + buffer.as_mut_ptr(), + buffer.len() as i32, + 0, + ) + }; + let display = if length > 0 { + text(&buffer) + } else { + user_locale.clone() + }; + + // A keyboard layout identifier such as 00020409; its low word is the + // language, giving upstream's `0409:00020409` notation. + let mut layout = [0u16; 9]; + // SAFETY: KL_NAMELENGTH is nine characters including the terminator. + let input_locale = (unsafe { GetKeyboardLayoutNameW(layout.as_mut_ptr()) } != 0) + .then(|| text(&layout)) + .filter(|klid| klid.len() == 8 && klid.chars().all(|c| c.is_ascii_hexdigit())) + .map(|klid| format!("{}:{}", &klid[4..], klid).to_ascii_lowercase()) + .unwrap_or_else(|| system_locale.clone()); + + // SAFETY: zero is a valid starting value for this plain structure. + let mut zone: DYNAMIC_TIME_ZONE_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: `zone` is writable; the key name is the stable English name. + let time_zone = (unsafe { GetDynamicTimeZoneInformation(&mut zone) } != TIME_ZONE_ID_INVALID) + .then(|| text(&zone.TimeZoneKeyName)) + .filter(|name| !name.is_empty()); + + RegionalSettings { + input_locale, + ui_language: ui_language(&display, image_languages), + user_locale, + system_locale, + time_zone, + } +} + +/// This session's regional settings, matched against the image's languages +/// so that Windows is never asked for a display language it does not have. +#[cfg(not(windows))] pub fn current(image_languages: &[String]) -> RegionalSettings { let env = |name: &str| std::env::var(name).ok().filter(|value| !value.is_empty()); let locale = |category: &str| { @@ -216,6 +293,17 @@ pub fn windows_zone(iana: &str) -> Option { mod tests { use super::*; + #[test] + fn this_session_yields_valid_answer_file_values() { + let customization = rufust_helper_protocol::WindowsCustomization { + regional: Some(current(&["en-US".to_owned()])), + ..Default::default() + }; + customization + .validate() + .expect("regional values pass validation"); + } + #[test] fn posix_locales_become_windows_tags() { assert_eq!(windows_locale("en_PH.UTF-8").as_deref(), Some("en-PH")); diff --git a/apps/rufust/src/settings.rs b/apps/rufust/src/settings.rs index bb160cd..d6b98ee 100644 --- a/apps/rufust/src/settings.rs +++ b/apps/rufust/src/settings.rs @@ -1,5 +1,6 @@ -//! Preferences kept across launches in -//! `$XDG_CONFIG_HOME/rufust/settings.conf` as `key=value` lines. +//! Preferences kept across launches as `key=value` lines in +//! `$XDG_CONFIG_HOME/rufust/settings.conf` on Linux and +//! `%APPDATA%Rufustsettings.conf` on Windows. use std::path::PathBuf; @@ -93,6 +94,19 @@ impl Settings { const CONFIG_DIR: &str = "rufust"; const LEGACY_CONFIG_DIR: &str = "rufus-linux"; +#[cfg(windows)] +fn path_in(dir: &str) -> Option { + // Rufus Linux never ran on Windows, so there is nothing to migrate. + if dir == LEGACY_CONFIG_DIR { + return None; + } + let base = std::env::var_os("APPDATA") + .map(PathBuf::from) + .filter(|path| path.is_absolute())?; + Some(base.join("Rufust").join("settings.conf")) +} + +#[cfg(not(windows))] fn path_in(dir: &str) -> Option { let base = std::env::var_os("XDG_CONFIG_HOME") .map(PathBuf::from) diff --git a/apps/rufust/src/state.rs b/apps/rufust/src/state.rs index c6dd439..f85599f 100644 --- a/apps/rufust/src/state.rs +++ b/apps/rufust/src/state.rs @@ -27,6 +27,11 @@ pub const DEFAULT_VOLUME_LABEL: &str = "RUFUST"; pub const SUPER_FLOPPY_LABEL: &str = "Super Floppy Disk"; /// Largest file FAT32 can store. const FAT32_MAX_FILE: u64 = 4 * 1024 * 1024 * 1024 - 1; +const REFS_UNAVAILABLE: &str = if cfg!(windows) { + "ReFS creation is not available on Windows." +} else { + "ReFS creation is unavailable on Linux." +}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum BootSelection { DiskOrIso, @@ -387,7 +392,7 @@ impl AppState { pub fn recompute(&mut self) { let mut hints = Vec::new(); if self.filesystem_label.starts_with("ReFS") { - hints.push("ReFS creation is unavailable on Linux.".to_owned()); + hints.push(REFS_UNAVAILABLE.to_owned()); } if self.boot_selection == BootSelection::FreeDos && !self.capabilities.supports(Capability::FreeDos) @@ -450,13 +455,21 @@ impl AppState { && !self.capabilities.supports(filesystem_capability) { if filesystem_name == "ReFS" { - return Some("ReFS creation is unavailable on Linux.".into()); + return Some(REFS_UNAVAILABLE.into()); + } + if cfg!(windows) { + return Some(format!( + "{filesystem_name} creation is not available on Windows yet." + )); } return Some(format!( "Install the formatter provider for {filesystem_name} to enable this option." )); } - let own_bad_block_test = matches!(self.backend, Ok(Backend::Udisks { .. })); + let own_bad_block_test = self + .backend + .as_ref() + .is_ok_and(Backend::has_own_bad_block_test); if self.check_bad_blocks && !own_bad_block_test && !self.capabilities.supports(Capability::BadBlocksCheck) @@ -498,7 +511,11 @@ impl AppState { .into(), ), Some(ImageSourceKind::Ffu) => { - Some("FFU apply is unavailable because Linux has no selected safe provider.".into()) + Some(if cfg!(windows) { + "FFU apply is not available yet.".into() + } else { + "FFU apply is unavailable because Linux has no selected safe provider.".into() + }) } Some(ImageSourceKind::None) => Some("Select a supported disk image.".into()), } @@ -828,9 +845,11 @@ impl AppState { .ok_or(PlanError::InvalidDevice("no device"))?; let filesystem = self.parse_filesystem()?; if filesystem == FileSystem::Refs { - return Err(PlanError::UnavailableCapability( - "ReFS creation is not available on Linux".into(), - )); + return Err(PlanError::UnavailableCapability(if cfg!(windows) { + "ReFS creation is not available on Windows".into() + } else { + "ReFS creation is not available on Linux".into() + })); } let write_mode = self.write_mode(); let partition = PartitionPlan { @@ -1100,11 +1119,21 @@ impl DeviceListLabel for BlockDevice { mod tests { use super::*; use rufust_core::device::{DeviceFingerprint, DeviceNumber, DeviceRisk, Transport}; + + /// Unix fixture paths, made absolute on Windows too. + fn test_path(unix: &str) -> std::path::PathBuf { + std::path::PathBuf::from(if cfg!(windows) { + format!("C:{unix}") + } else { + unix.to_owned() + }) + } + use std::path::PathBuf; fn sample_device() -> BlockDevice { BlockDevice { - node: PathBuf::from("/dev/sdb"), + node: test_path("/dev/sdb"), display_name: "Test Stick".into(), vendor: Some("Test".into()), model: Some("Stick".into()), @@ -1112,7 +1141,7 @@ mod tests { transport: Transport::Usb, fingerprint: DeviceFingerprint { number: DeviceNumber::new(8, 16), - canonical_sysfs_path: PathBuf::from("/sys/devices/example"), + canonical_sysfs_path: test_path("/sys/devices/example"), size_bytes: 32 * 1024 * 1024 * 1024, logical_block_size: 512, serial: Some("SN".into()), diff --git a/apps/rufust/ui/appwindow.slint b/apps/rufust/ui/appwindow.slint index 5e4735a..6eb6fd2 100644 --- a/apps/rufust/ui/appwindow.slint +++ b/apps/rufust/ui/appwindow.slint @@ -94,6 +94,7 @@ export component AppWindow inherits Window { in-out property show-advanced: false; in-out property capability-hint: ""; in-out property app-version: "1.1.0"; + in property privilege-note: "Destructive writes use a polkit-authorized helper. The desktop process never holds ambient root for raw disks."; // —— Callbacks —— callback refresh-devices(); @@ -666,14 +667,14 @@ export component AppWindow inherits Window { } } Text { - text: "Independent Linux port inspired by Rufus. Formats and writes bootable removable media under GPLv3. Not affiliated with upstream Rufus maintainers."; + text: "Independent Linux and Windows port inspired by Rufus. Formats and writes bootable removable media under GPLv3. Not affiliated with upstream Rufus maintainers."; color: Theme.text; font-family: Theme.body-font; font-size: 13px; wrap: word-wrap; } Text { - text: "Destructive writes use a polkit-authorized helper. The desktop process never holds ambient root for raw disks."; + text: root.privilege-note; color: Theme.muted; font-family: Theme.body-font; font-size: 12px; diff --git a/crates/rufust-core/src/device.rs b/crates/rufust-core/src/device.rs index a535e23..747cb26 100644 --- a/crates/rufust-core/src/device.rs +++ b/crates/rufust-core/src/device.rs @@ -135,6 +135,15 @@ impl BlockDevice { mod tests { use super::*; + /// Unix fixture paths, made absolute on Windows too. + fn test_path(unix: &str) -> std::path::PathBuf { + std::path::PathBuf::from(if cfg!(windows) { + format!("C:{unix}") + } else { + unix.to_owned() + }) + } + #[test] fn fingerprint_requires_sane_block_geometry() { let mut fingerprint = fingerprint(); @@ -156,7 +165,7 @@ mod tests { fn fingerprint() -> DeviceFingerprint { DeviceFingerprint { number: DeviceNumber::new(8, 16), - canonical_sysfs_path: PathBuf::from("/sys/devices/example"), + canonical_sysfs_path: test_path("/sys/devices/example"), size_bytes: 16 * 1024 * 1024, logical_block_size: 512, serial: Some("serial".into()), diff --git a/crates/rufust-core/src/plan.rs b/crates/rufust-core/src/plan.rs index 92882f6..7ba7af3 100644 --- a/crates/rufust-core/src/plan.rs +++ b/crates/rufust-core/src/plan.rs @@ -392,22 +392,30 @@ mod tests { use super::*; use crate::device::{DeviceFingerprint, DeviceNumber}; use crate::progress::JobId; - use std::path::PathBuf; + + /// Unix fixture paths, made absolute on Windows too. + fn test_path(unix: &str) -> std::path::PathBuf { + std::path::PathBuf::from(if cfg!(windows) { + format!("C:{unix}") + } else { + unix.to_owned() + }) + } fn sample_plan() -> OperationPlan { OperationPlan { job_id: JobId::new(1), - target_node: PathBuf::from("/dev/sdb"), + target_node: test_path("/dev/sdb"), target_fingerprint: DeviceFingerprint { number: DeviceNumber::new(8, 16), - canonical_sysfs_path: PathBuf::from("/sys/devices/example"), + canonical_sysfs_path: test_path("/sys/devices/example"), size_bytes: 32 * 1024 * 1024 * 1024, logical_block_size: 512, serial: Some("ABC".into()), wwn: None, }, source: Some(ImageSource { - path: PathBuf::from("/tmp/test.iso"), + path: test_path("/tmp/test.iso"), kind: ImageSourceKind::Iso, size_bytes: 700 * 1024 * 1024, decompressed_size_bytes: None, diff --git a/crates/rufust-core/src/safety.rs b/crates/rufust-core/src/safety.rs index a0c3bcc..78834a5 100644 --- a/crates/rufust-core/src/safety.rs +++ b/crates/rufust-core/src/safety.rs @@ -195,15 +195,23 @@ pub fn confirmation_message( #[cfg(test)] mod tests { + /// Unix fixture paths, made absolute on Windows too. + fn test_path(unix: &str) -> std::path::PathBuf { + std::path::PathBuf::from(if cfg!(windows) { + format!("C:{unix}") + } else { + unix.to_owned() + }) + } + use super::*; use crate::device::{ BlockDevice, DeviceClass, DeviceFingerprint, DeviceNumber, DeviceRisk, Transport, }; - use std::path::PathBuf; fn device(class: DeviceClass, risks: Vec) -> BlockDevice { BlockDevice { - node: PathBuf::from("/dev/sdb"), + node: test_path("/dev/sdb"), display_name: "Test Stick".into(), vendor: Some("Test".into()), model: Some("Stick".into()), @@ -211,7 +219,7 @@ mod tests { transport: Transport::Usb, fingerprint: DeviceFingerprint { number: DeviceNumber::new(8, 16), - canonical_sysfs_path: PathBuf::from("/sys/devices/example"), + canonical_sysfs_path: test_path("/sys/devices/example"), size_bytes: 16 * 1024 * 1024 * 1024, logical_block_size: 512, serial: Some("SN".into()), diff --git a/crates/rufust-helper-protocol/src/lib.rs b/crates/rufust-helper-protocol/src/lib.rs index 2b2724e..865424f 100644 --- a/crates/rufust-helper-protocol/src/lib.rs +++ b/crates/rufust-helper-protocol/src/lib.rs @@ -340,18 +340,27 @@ mod serde_impls { mod tests { use super::*; use rufust_core::device::DeviceNumber; + + /// Unix fixture paths, made absolute on Windows too. + fn test_path(unix: &str) -> std::path::PathBuf { + std::path::PathBuf::from(if cfg!(windows) { + format!("C:{unix}") + } else { + unix.to_owned() + }) + } + use rufust_core::plan::{PartitionScheme, VerificationLevel, WriteMode}; - use std::path::PathBuf; fn sample_request() -> HelperRequest { HelperRequest { protocol_version: PROTOCOL_VERSION, job_id: JobId::new(42), target: TargetIdentity { - node: PathBuf::from("/dev/sdb"), + node: test_path("/dev/sdb"), fingerprint: DeviceFingerprint { number: DeviceNumber::new(8, 16), - canonical_sysfs_path: PathBuf::from("/sys/devices/pci0000:00/usb"), + canonical_sysfs_path: test_path("/sys/devices/pci0000:00/usb"), size_bytes: 32_000_000_000, logical_block_size: 512, serial: Some("SN123".into()), @@ -364,7 +373,7 @@ mod tests { operation: HelperOperation::WriteMedia { write_mode: WriteMode::DdImage, source: SourceSpec { - path: PathBuf::from("/home/user/image.iso"), + path: test_path("/home/user/image.iso"), kind: ImageSourceKind::Iso, size_bytes: 700_000_000, decompressed_size_bytes: None, diff --git a/crates/rufust-helper/Cargo.toml b/crates/rufust-helper/Cargo.toml index 555fc7d..b0aced0 100644 --- a/crates/rufust-helper/Cargo.toml +++ b/crates/rufust-helper/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rufust-helper" -description = "Privileged helper for raw-device operations (polkit-authorized)" +description = "Disk operation engines for Rufust: udisks2 and the polkit helper on Linux, an elevated worker on Windows" version.workspace = true edition.workspace = true rust-version.workspace = true @@ -24,7 +24,26 @@ fs2 = "0.4" sha2 = "0.10" libc = "0.2" rufust-image = { path = "../rufust-image" } + +[target.'cfg(target_os = "linux")'.dependencies] zbus = { version = "4.4", default-features = false, features = ["async-io"] } +[target.'cfg(windows)'.dependencies] +bzip2 = "0.6" +flate2 = "1" +lzma-rust2 = { version = "0.15", default-features = false, features = ["std", "xz"] } +ruzstd = { version = "0.7", default-features = false, features = ["std"] } +windows-sys = { version = "0.59", features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_Storage_FileSystem", + "Win32_Storage_Vhd", + "Win32_System_Com", + "Win32_System_IO", + "Win32_System_Ioctl", + "Win32_System_LibraryLoader", + "Win32_System_Threading", +] } + [dev-dependencies] rufust-image = { path = "../rufust-image", features = ["fixtures"] } diff --git a/crates/rufust-helper/src/engine.rs b/crates/rufust-helper/src/engine.rs new file mode 100644 index 0000000..1c193a5 --- /dev/null +++ b/crates/rufust-helper/src/engine.rs @@ -0,0 +1,140 @@ +//! Progress reporting and Windows-media planning shared by the udisks2 and +//! Windows disk engines. + +use std::fs::File; +use std::time::{Duration, Instant}; + +use rufust_helper_protocol::{HelperEvent, WindowsCustomization}; +use rufust_image::isofs; + +use crate::{ + emit, progress, unattend, Cancellability, EventSink, HelperError, JobId, ProgressStage, + ProgressUnit, +}; + +pub(crate) const MIB: u64 = 1024 * 1024; + +/// Stage and byte progress for one job. +pub(crate) struct Reporter<'a> { + pub(crate) job_id: JobId, + pub(crate) sink: &'a mut EventSink, + pub(crate) step: u64, + pub(crate) total: u64, +} + +impl Reporter<'_> { + pub(crate) fn stage(&mut self, stage: ProgressStage, detail: &str) { + let event = progress( + self.job_id, + stage, + self.step, + Some(self.total), + Some(detail.to_owned()), + ); + emit(self.sink, event); + self.step = (self.step + 1).min(self.total); + } + + pub(crate) fn log(&mut self, line: impl Into) { + let event = HelperEvent::Log { + job_id: self.job_id, + line: line.into(), + }; + emit(self.sink, event); + } + + pub(crate) fn bytes( + &mut self, + stage: ProgressStage, + meter: &mut Meter, + done: u64, + detail: &str, + ) { + if !meter.due(done) { + return; + } + let event = HelperEvent::Progress { + job_id: self.job_id, + stage, + unit: ProgressUnit::Bytes, + completed: done, + total: Some(meter.total), + bytes_per_second: Some(meter.rate(done)), + detail: Some(detail.to_owned()), + cancellability: Cancellability::Immediate, + }; + emit(self.sink, event); + } +} + +pub(crate) struct Meter { + pub(crate) total: u64, + started: Instant, + last: Option, +} + +impl Meter { + pub(crate) fn new(total: u64) -> Self { + Self { + total, + started: Instant::now(), + last: None, + } + } + + pub(crate) fn due(&mut self, done: u64) -> bool { + let now = Instant::now(); + if done < self.total + && self + .last + .is_some_and(|last| now.duration_since(last) < Duration::from_millis(200)) + { + return false; + } + self.last = Some(now); + true + } + + pub(crate) fn rate(&self, done: u64) -> u64 { + (done as f64 / self.started.elapsed().as_secs_f64().max(0.001)) as u64 + } +} + +/// Read the image's Windows details and refuse customization it cannot take. +pub(crate) fn customization_plan( + iso: &mut File, + listing: &isofs::IsoListing, + options: &WindowsCustomization, +) -> Result<(unattend::AnswerFile, u32), HelperError> { + let windows = rufust_image::windows::inspect(iso, listing) + .filter(|windows| windows.is_windows_10_or_later()) + .ok_or_else(|| { + HelperError::Operation( + "Windows User Experience options need Windows 10 or later media".into(), + ) + })?; + if windows.has_panther_unattend || listing.has_file(unattend::ROOT_ANSWER_FILE) { + return Err(HelperError::Operation( + "this image already has its own answer file".into(), + )); + } + if let Some(index) = options.silent_install_index { + if !windows + .editions + .iter() + .any(|edition| edition.index == index) + { + return Err(HelperError::Operation(format!( + "this image has no Windows edition {index}" + ))); + } + } + let arch = windows.arch.ok_or_else(|| { + HelperError::Operation("the Windows architecture of this image is unknown".into()) + })?; + let language = windows.setup_language.as_deref().unwrap_or("en-US"); + Ok(( + unattend::answer_file(options, arch, language), + windows.build, + )) +} diff --git a/crates/rufust-helper/src/fat32.rs b/crates/rufust-helper/src/fat32.rs new file mode 100644 index 0000000..70a3984 --- /dev/null +++ b/crates/rufust-helper/src/fat32.rs @@ -0,0 +1,345 @@ +//! FAT32 for volumes Windows' own formatter refuses (over 32 GB), after +//! upstream Rufus's `FormatLargeFAT32`, itself from Tom Thornhill's +//! fat32format. The layout is computed here and written through a +//! sector-aligned callback, so it is testable on any platform. + +use std::io; + +use rufust_core::progress::CancellationToken; + +use crate::{check_cancel, HelperError}; + +const KIB: u64 = 1024; +const MIB: u64 = 1024 * KIB; +const GIB: u64 = 1024 * MIB; +const RESERVED_SECTORS: u32 = 32; +const BACKUP_BOOT_SECTOR: u32 = 6; +const FAT_COUNT: u32 = 2; +/// Fewer clusters than this would be read as FAT16. +const MIN_CLUSTERS: u64 = 65_536; +/// The top four bits of a FAT32 entry are reserved. +const MAX_CLUSTERS: u64 = 0x0FFF_FFFF; + +/// Where each region of a FAT32 volume goes, in sectors. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Layout { + pub bytes_per_sector: u32, + pub sectors_per_cluster: u32, + pub reserved_sectors: u32, + pub fat_sectors: u32, + pub total_sectors: u32, + pub clusters: u32, +} + +impl Layout { + /// Reserved area, both FATs, and the root directory's cluster. + fn system_sectors(&self) -> u64 { + u64::from(self.reserved_sectors) + + u64::from(FAT_COUNT) * u64::from(self.fat_sectors) + + u64::from(self.sectors_per_cluster) + } +} + +/// Microsoft's default FAT32 cluster size for a volume of `bytes`. +pub(crate) fn default_cluster_size(bytes: u64) -> u32 { + match bytes { + b if b < 64 * MIB => 512, + b if b < 128 * MIB => 1024, + b if b < 256 * MIB => 2048, + b if b < 8 * GIB => 4096, + b if b < 16 * GIB => 8192, + b if b < 32 * GIB => 16_384, + b if b < 2048 * GIB => 32_768, + _ => 65_536, + } +} + +pub(crate) fn plan( + volume_bytes: u64, + bytes_per_sector: u32, + cluster_size: Option, +) -> Result { + let refuse = |message: &str| Err(HelperError::Operation(message.into())); + if !(512..=4096).contains(&bytes_per_sector) || !bytes_per_sector.is_power_of_two() { + return refuse("FAT32 needs 512- to 4096-byte sectors"); + } + let total = volume_bytes / u64::from(bytes_per_sector); + if total < 65_536 { + return refuse("this volume is too small for FAT32"); + } + let Ok(total_sectors) = u32::try_from(total) else { + return refuse("this volume is too large for FAT32 (2 TB with 512-byte sectors)"); + }; + let cluster = cluster_size.unwrap_or_else(|| default_cluster_size(volume_bytes)); + if cluster < bytes_per_sector || cluster % bytes_per_sector != 0 || cluster > 65_536 { + return refuse("this cluster size does not suit FAT32 on this drive"); + } + let sectors_per_cluster = cluster / bytes_per_sector; + if !sectors_per_cluster.is_power_of_two() || sectors_per_cluster > 128 { + return refuse("this cluster size does not suit FAT32 on this drive"); + } + + // GetFATSizeSectors: the +1 rounds up. + let numerator = total - u64::from(RESERVED_SECTORS) + 2 * u64::from(sectors_per_cluster); + let denominator = + u64::from(sectors_per_cluster) * u64::from(bytes_per_sector) / 4 + u64::from(FAT_COUNT); + let fat_sectors = numerator / denominator + 1; + + // Grow the reserved area so the data region starts on a 1 MiB boundary. + let align = MIB / u64::from(bytes_per_sector); + let system = u64::from(RESERVED_SECTORS) + u64::from(FAT_COUNT) * fat_sectors; + let system = system.div_ceil(align) * align; + let reserved = system - u64::from(FAT_COUNT) * fat_sectors; + let Ok(reserved_sectors) = u16::try_from(reserved).map(u32::from) else { + return refuse("FAT32 reserved area is too large"); + }; + + let data = total.saturating_sub(reserved + u64::from(FAT_COUNT) * fat_sectors); + let clusters = data / u64::from(sectors_per_cluster); + if clusters < MIN_CLUSTERS { + return refuse("FAT32 needs at least 65536 clusters; choose a smaller cluster size"); + } + if clusters > MAX_CLUSTERS { + return refuse("too many FAT32 clusters; choose a larger cluster size"); + } + if (clusters * 4).div_ceil(u64::from(bytes_per_sector)) > fat_sectors { + return refuse("the FAT would not cover this volume"); + } + Ok(Layout { + bytes_per_sector, + sectors_per_cluster, + reserved_sectors, + fat_sectors: u32::try_from(fat_sectors).unwrap_or(u32::MAX), + total_sectors, + clusters: u32::try_from(clusters).unwrap_or(u32::MAX), + }) +} + +/// The 11-byte BPB label: upper case, padded, `NO NAME` when empty. +pub(crate) fn bpb_label(label: &str) -> [u8; 11] { + let mut bytes = [b' '; 11]; + let cleaned = label + .chars() + .filter(|c| c.is_ascii() && !c.is_ascii_control()) + .map(|c| match c.to_ascii_uppercase() { + '"' | '*' | '+' | ',' | '.' | '/' | ':' | ';' | '<' | '=' | '>' | '?' | '[' | '\\' + | ']' | '|' => '_', + other => other, + }) + .take(11) + .collect::(); + if cleaned.trim().is_empty() { + bytes.copy_from_slice(b"NO NAME "); + } else { + bytes[..cleaned.len()].copy_from_slice(cleaned.as_bytes()); + } + bytes +} + +fn put16(sector: &mut [u8], at: usize, value: u16) { + sector[at..at + 2].copy_from_slice(&value.to_le_bytes()); +} + +fn put32(sector: &mut [u8], at: usize, value: u32) { + sector[at..at + 4].copy_from_slice(&value.to_le_bytes()); +} + +pub(crate) fn boot_sector( + layout: &Layout, + hidden_sectors: u32, + volume_id: u32, + label: &str, +) -> Vec { + let mut sector = vec![0u8; layout.bytes_per_sector as usize]; + sector[..3].copy_from_slice(&[0xEB, 0x58, 0x90]); + sector[3..11].copy_from_slice(b"MSWIN4.1"); + put16(&mut sector, 11, layout.bytes_per_sector as u16); + sector[13] = layout.sectors_per_cluster as u8; + put16(&mut sector, 14, layout.reserved_sectors as u16); + sector[16] = FAT_COUNT as u8; + sector[21] = 0xF8; + put16(&mut sector, 24, 63); + put16(&mut sector, 26, 255); + put32(&mut sector, 28, hidden_sectors); + put32(&mut sector, 32, layout.total_sectors); + put32(&mut sector, 36, layout.fat_sectors); + put32(&mut sector, 44, 2); + put16(&mut sector, 48, 1); + put16(&mut sector, 50, BACKUP_BOOT_SECTOR as u16); + sector[64] = 0x80; + sector[66] = 0x29; + put32(&mut sector, 67, volume_id); + sector[71..82].copy_from_slice(&bpb_label(label)); + sector[82..90].copy_from_slice(b"FAT32 "); + sector[510] = 0x55; + sector[511] = 0xAA; + let end = sector.len(); + sector[end - 2] = 0x55; + sector[end - 1] = 0xAA; + sector +} + +pub(crate) fn fs_info(layout: &Layout) -> Vec { + let mut sector = vec![0u8; layout.bytes_per_sector as usize]; + put32(&mut sector, 0, 0x4161_5252); + put32(&mut sector, 484, 0x6141_7272); + // The root directory takes cluster 2. + put32(&mut sector, 488, layout.clusters - 1); + put32(&mut sector, 492, 3); + put32(&mut sector, 508, 0xAA55_0000); + sector +} + +pub(crate) fn first_fat_sector(layout: &Layout) -> Vec { + let mut sector = vec![0u8; layout.bytes_per_sector as usize]; + put32(&mut sector, 0, 0x0FFF_FFF8); + put32(&mut sector, 4, 0x0FFF_FFFF); + put32(&mut sector, 8, 0x0FFF_FFFF); + sector +} + +/// Write a fresh FAT32 file system through `write_at(byte offset, bytes)`. +/// Every write is a whole number of sectors at a sector-aligned offset. +pub(crate) fn write( + layout: &Layout, + hidden_sectors: u32, + volume_id: u32, + label: &str, + cancel: &CancellationToken, + write_at: &mut dyn FnMut(u64, &[u8]) -> io::Result<()>, +) -> Result<(), HelperError> { + let sector = u64::from(layout.bytes_per_sector); + let zeros = vec![0u8; MIB as usize]; + let system = layout.system_sectors() * sector; + let mut offset = 0; + while offset < system { + check_cancel(cancel)?; + let length = (system - offset).min(MIB) as usize; + write_at(offset, &zeros[..length])?; + offset += length as u64; + } + let boot = boot_sector(layout, hidden_sectors, volume_id, label); + let info = fs_info(layout); + for start in [0, u64::from(BACKUP_BOOT_SECTOR)] { + write_at(start * sector, &boot)?; + write_at((start + 1) * sector, &info)?; + } + let fat = first_fat_sector(layout); + for index in 0..u64::from(FAT_COUNT) { + let start = u64::from(layout.reserved_sectors) + index * u64::from(layout.fat_sectors); + write_at(start * sector, &fat)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn u16_at(bytes: &[u8], at: usize) -> u16 { + u16::from_le_bytes([bytes[at], bytes[at + 1]]) + } + + fn u32_at(bytes: &[u8], at: usize) -> u32 { + u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes")) + } + + #[test] + fn large_volumes_get_microsoft_defaults_and_aligned_data() { + for (size, sector) in [(64 * GIB, 512), (128 * GIB, 512), (256 * GIB, 4096)] { + let layout = plan(size, sector, None).expect("FAT32 layout"); + assert_eq!( + layout.sectors_per_cluster * sector, + default_cluster_size(size) + ); + let data_start = u64::from(layout.reserved_sectors) + + u64::from(FAT_COUNT) * u64::from(layout.fat_sectors); + assert_eq!(data_start * u64::from(sector) % MIB, 0); + assert!(u64::from(layout.clusters) >= MIN_CLUSTERS); + assert!( + u64::from(layout.clusters) * 4 <= u64::from(layout.fat_sectors) * u64::from(sector) + ); + } + assert_eq!(default_cluster_size(64 * GIB), 32 * 1024); + assert_eq!(default_cluster_size(3 * 1024 * GIB), 64 * 1024); + } + + #[test] + fn impossible_volumes_are_refused() { + assert!(plan(16 * MIB, 512, None).is_err()); + assert!(plan(3 * 1024 * GIB, 512, None).is_err()); + assert!(plan(64 * GIB, 512, Some(1000)).is_err()); + assert!(plan(64 * GIB, 520, None).is_err()); + // Too few clusters to be FAT32. + assert!(plan(64 * MIB, 512, Some(65_536)).is_err()); + } + + #[test] + fn labels_follow_the_bpb_rules() { + assert_eq!(&bpb_label("rufust"), b"RUFUST "); + assert_eq!(&bpb_label(""), b"NO NAME "); + assert_eq!(&bpb_label("a.b:c"), b"A_B_C "); + assert_eq!(&bpb_label("ABCDEFGHIJKLMN"), b"ABCDEFGHIJK"); + } + + #[test] + fn writes_a_mountable_layout() { + let size = 40 * MIB; + let layout = plan(size, 512, Some(512)).expect("layout"); + let mut disk = vec![0xEEu8; size as usize]; + write( + &layout, + 2048, + 0x1234_5678, + "Rufust", + &CancellationToken::new(), + &mut |offset, bytes| { + assert_eq!(offset % 512, 0); + assert_eq!(bytes.len() % 512, 0); + let at = offset as usize; + disk[at..at + bytes.len()].copy_from_slice(bytes); + Ok(()) + }, + ) + .expect("format"); + + let boot = &disk[..512]; + assert_eq!(&boot[510..], &[0x55, 0xAA]); + assert_eq!(u16_at(boot, 11), 512); + assert_eq!(u16_at(boot, 14), layout.reserved_sectors as u16); + assert_eq!(u32_at(boot, 28), 2048); + assert_eq!(u32_at(boot, 32), (size / 512) as u32); + assert_eq!(u32_at(boot, 36), layout.fat_sectors); + assert_eq!(u32_at(boot, 67), 0x1234_5678); + assert_eq!(&boot[71..82], b"RUFUST "); + assert_eq!(&boot[82..90], b"FAT32 "); + assert_eq!(&disk[6 * 512..7 * 512], boot); + + let info = &disk[512..1024]; + assert_eq!(u32_at(info, 0), 0x4161_5252); + assert_eq!(u32_at(info, 484), 0x6141_7272); + assert_eq!(u32_at(info, 488), layout.clusters - 1); + assert_eq!(u32_at(info, 508), 0xAA55_0000); + + for index in 0..FAT_COUNT { + let at = ((layout.reserved_sectors + index * layout.fat_sectors) * 512) as usize; + assert_eq!(u32_at(&disk, at), 0x0FFF_FFF8); + assert_eq!(u32_at(&disk, at + 8), 0x0FFF_FFFF); + assert!(disk[at + 12..at + 512].iter().all(|byte| *byte == 0)); + } + // The root directory cluster is empty, and nothing past it was touched. + let root = (layout.system_sectors() - u64::from(layout.sectors_per_cluster)) * 512; + let end = layout.system_sectors() * 512; + assert!(disk[root as usize..end as usize].iter().all(|b| *b == 0)); + assert_eq!(disk[end as usize], 0xEE); + } + + #[test] + fn cancellation_stops_before_the_boot_sector() { + let layout = plan(40 * MIB, 512, Some(512)).expect("layout"); + let cancel = CancellationToken::new(); + cancel.request(); + let result = write(&layout, 0, 1, "", &cancel, &mut |_, _| Ok(())); + assert!(matches!(result, Err(HelperError::Cancelled))); + } +} diff --git a/crates/rufust-helper/src/lib.rs b/crates/rufust-helper/src/lib.rs index ff14b6e..156106b 100644 --- a/crates/rufust-helper/src/lib.rs +++ b/crates/rufust-helper/src/lib.rs @@ -1,44 +1,85 @@ -//! Disk operation engines. The root helper binary is a thin CLI around -//! [`execute`]; [`execute_with_udisks`] runs the same operations as the -//! desktop user through the system udisks2 daemon. +//! Disk operation engines. +//! +//! On Linux, the root helper binary is a thin CLI around [`execute`], and +//! [`execute_with_udisks`] runs the same operations as the desktop user +//! through the system udisks2 daemon. On Windows, [`execute`] runs in an +//! elevated worker that the desktop starts through UAC and drives over a +//! private named pipe ([`serve_pipe`]). + +use std::io::{self, Write}; +use std::path::PathBuf; +use std::time::{SystemTime, UNIX_EPOCH}; + +use rufust_core::plan::{FileSystem, PartitionScheme}; +use rufust_core::progress::{ + Cancellability, CancellationToken, JobId, ProgressStage, ProgressUnit, +}; +use rufust_helper_protocol::{ + encode_line, FormatSpec, HelperEvent, HelperOperation, HelperRequest, ProtocolError, + TargetIdentity, +}; +use rufust_platform::PlatformError; +use thiserror::Error; +#[cfg(target_os = "linux")] use std::ffi::{CStr, CString}; +#[cfg(target_os = "linux")] use std::fs::File; -use std::io::{self, Read, Seek, SeekFrom, Write}; +#[cfg(target_os = "linux")] +use std::io::{Read, Seek, SeekFrom}; +#[cfg(target_os = "linux")] use std::os::fd::AsRawFd; +#[cfg(target_os = "linux")] use std::os::unix::fs::{FileTypeExt, MetadataExt, OpenOptionsExt}; +#[cfg(target_os = "linux")] use std::os::unix::process::CommandExt; -use std::path::{Path, PathBuf}; +#[cfg(target_os = "linux")] +use std::path::Path; +#[cfg(target_os = "linux")] use std::process::{Child, Command, ExitStatus, Stdio}; +#[cfg(target_os = "linux")] use std::ptr; -use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; +#[cfg(target_os = "linux")] +use std::time::{Duration, Instant}; +#[cfg(target_os = "linux")] use fs2::FileExt; -use rufust_core::plan::{FileSystem, PartitionScheme, VerificationLevel, WriteMode}; -use rufust_core::progress::{ - Cancellability, CancellationToken, JobId, ProgressStage, ProgressUnit, -}; -use rufust_helper_protocol::{ - encode_line, FormatSpec, HelperEvent, HelperOperation, HelperRequest, HelperResult, - ProtocolError, TargetIdentity, -}; -use rufust_platform::{ - discover_devices, mount_belongs_to_identity, mount_records, DeviceIdentity, PlatformError, -}; +#[cfg(target_os = "linux")] +use rufust_core::plan::{VerificationLevel, WriteMode}; +#[cfg(target_os = "linux")] +use rufust_helper_protocol::HelperResult; +#[cfg(target_os = "linux")] +use rufust_platform::{discover_devices, mount_belongs_to_identity, mount_records, DeviceIdentity}; +#[cfg(target_os = "linux")] use sha2::{Digest, Sha256}; -use thiserror::Error; pub const HELPER_VERSION: &str = env!("CARGO_PKG_VERSION"); +#[cfg(target_os = "linux")] const DECODER_IDLE_TIMEOUT: Duration = Duration::from_secs(120); +mod engine; +#[cfg(any(windows, test))] +mod fat32; +#[cfg(target_os = "linux")] mod source_snapshot; +#[cfg(target_os = "linux")] mod udisks; +#[cfg(target_os = "linux")] mod udisks_engine; mod unattend; +#[cfg(target_os = "linux")] mod virtual_disk; +#[cfg(windows)] +mod windows; mod windows_media; +#[cfg(target_os = "linux")] pub use udisks_engine::{execute_with_udisks, udisks_readiness, validate_udisks_request}; +#[cfg(windows)] +pub use windows::{ + execute, inspect_virtual_disk_for_user, is_elevated, revalidate_target, serve_pipe, + validate_request, +}; #[derive(Debug, Error)] pub enum HelperError { @@ -63,6 +104,7 @@ pub enum HelperError { /// This preview is advisory: a read-only descriptor does not prevent another /// process from changing its inode. Execution must protect and inspect the /// source again before preparing the target. The descriptor's offset may move. +#[cfg(target_os = "linux")] pub fn inspect_virtual_disk_for_user( source: &File, kind: rufust_core::plan::ImageSourceKind, @@ -95,6 +137,7 @@ pub fn inspect_virtual_disk_for_user( } /// Fixed absolute paths for formatters. Never taken from the environment. +#[cfg(target_os = "linux")] pub mod tools { pub const PARTED: &[&str] = &["/usr/sbin/parted", "/usr/bin/parted", "/sbin/parted"]; pub const MKFS_FAT: &[&str] = &["/usr/sbin/mkfs.fat", "/usr/bin/mkfs.fat", "/sbin/mkfs.fat"]; @@ -126,6 +169,7 @@ pub mod tools { pub const BSDTAR: &[&str] = &["/usr/bin/bsdtar", "/bin/bsdtar"]; } +#[cfg(target_os = "linux")] fn find_tool(candidates: &'static [&'static str]) -> Result<&'static str, HelperError> { candidates .iter() @@ -134,6 +178,7 @@ fn find_tool(candidates: &'static [&'static str]) -> Result<&'static str, Helper .ok_or_else(|| HelperError::MissingTool(candidates.join(" or "))) } +#[cfg(target_os = "linux")] #[derive(Clone, Debug)] struct InvokingUser { uid: libc::uid_t, @@ -141,6 +186,7 @@ struct InvokingUser { username: CString, } +#[cfg(target_os = "linux")] impl InvokingUser { fn for_execution() -> Result { let effective_uid = unsafe { libc::geteuid() }; @@ -215,12 +261,14 @@ impl InvokingUser { } } +#[cfg(target_os = "linux")] fn parse_pkexec_uid(value: &str) -> Result { value.parse::().map_err(|_| { HelperError::Operation("PKEXEC_UID must be an unsigned numeric user id".into()) }) } +#[cfg(target_os = "linux")] fn supplementary_groups() -> Result, HelperError> { let count = unsafe { libc::getgroups(0, ptr::null_mut()) }; if count < 0 { @@ -236,6 +284,7 @@ fn supplementary_groups() -> Result, HelperError> { Ok(groups) } +#[cfg(target_os = "linux")] fn set_supplementary_groups(groups: &[libc::gid_t]) -> io::Result<()> { let pointer = if groups.is_empty() { ptr::null() @@ -248,6 +297,7 @@ fn set_supplementary_groups(groups: &[libc::gid_t]) -> io::Result<()> { Ok(()) } +#[cfg(target_os = "linux")] fn set_effective_uid(uid: libc::uid_t) -> io::Result<()> { if unsafe { libc::seteuid(uid) } != 0 { return Err(io::Error::last_os_error()); @@ -255,6 +305,7 @@ fn set_effective_uid(uid: libc::uid_t) -> io::Result<()> { Ok(()) } +#[cfg(target_os = "linux")] fn set_effective_gid(gid: libc::gid_t) -> io::Result<()> { if unsafe { libc::setegid(gid) } != 0 { return Err(io::Error::last_os_error()); @@ -262,6 +313,7 @@ fn set_effective_gid(gid: libc::gid_t) -> io::Result<()> { Ok(()) } +#[cfg(target_os = "linux")] fn restore_root_credentials( original_gid: libc::gid_t, original_groups: &[libc::gid_t], @@ -272,6 +324,7 @@ fn restore_root_credentials( Ok(()) } +#[cfg(target_os = "linux")] fn open_source_as_user(path: &Path, user: &InvokingUser) -> Result { let open = || { std::fs::OpenOptions::new() @@ -308,6 +361,7 @@ fn open_source_as_user(path: &Path, user: &InvokingUser) -> Result Result { let source_device = source.metadata()?.dev(); let source_sysfs = PathBuf::from(format!( @@ -341,6 +396,7 @@ fn source_is_on_target(source: &File, target: &DeviceIdentity) -> Result Result<&'static str, HelperError> { let candidates = match fs { FileSystem::Fat | FileSystem::Fat32 => tools::MKFS_FAT, @@ -358,6 +414,7 @@ pub fn tool_for_filesystem(fs: FileSystem) -> Result<&'static str, HelperError> } /// Re-resolve the target and compare fingerprints strictly. +#[cfg(target_os = "linux")] pub fn revalidate_target(expected: &TargetIdentity) -> Result { let devices = discover_devices(true)?; let observed = devices @@ -407,6 +464,7 @@ pub fn revalidate_target(expected: &TargetIdentity) -> Result Result { let class_path = Path::new("/sys/class/block").join(&device.kernel_name); let mut nodes = vec![class_path.clone()]; @@ -468,6 +527,7 @@ fn sysfs_has_holders(device: &DeviceIdentity) -> Result { } /// Validate a request without performing destructive I/O. +#[cfg(target_os = "linux")] pub fn validate_request(request: &HelperRequest) -> Result<(), HelperError> { request.validate()?; match &request.operation { @@ -560,12 +620,14 @@ fn check_cancel(cancel: &CancellationToken) -> Result<(), HelperError> { } } +#[cfg(target_os = "linux")] struct ManagedChild { child: Child, process_group: libc::pid_t, reaped: bool, } +#[cfg(target_os = "linux")] impl ManagedChild { fn spawn(command: &mut Command, context: &str) -> Result { // SAFETY: only async-signal-safe syscalls run between fork and exec. @@ -721,6 +783,7 @@ impl ManagedChild { } } +#[cfg(target_os = "linux")] impl Drop for ManagedChild { fn drop(&mut self) { if !self.reaped { @@ -731,6 +794,7 @@ impl Drop for ManagedChild { } } +#[cfg(target_os = "linux")] fn run_command( command: &mut Command, cancel: &CancellationToken, @@ -764,6 +828,7 @@ fn progress( } /// Execute (or dry-run) a validated helper request. +#[cfg(target_os = "linux")] pub fn execute( mut request: HelperRequest, options: ExecutionOptions, @@ -1119,6 +1184,7 @@ pub fn execute( Ok(result) } +#[cfg(target_os = "linux")] struct PartitionFormatContext<'a> { job_id: JobId, dry_run: bool, @@ -1128,6 +1194,7 @@ struct PartitionFormatContext<'a> { cancel: &'a CancellationToken, } +#[cfg(target_os = "linux")] fn run_partition_format( target_node: &Path, format: &FormatSpec, @@ -1185,6 +1252,7 @@ fn run_partition_format( Ok(()) } +#[cfg(target_os = "linux")] fn unmount_target( identity: &DeviceIdentity, cancel: &CancellationToken, @@ -1237,6 +1305,7 @@ fn unmount_target( Ok(()) } +#[cfg(target_os = "linux")] fn parse_swap_sources(input: &str) -> Result, &'static str> { let mut lines = input.lines(); let header = lines.next().ok_or("swap state is empty")?; @@ -1259,6 +1328,7 @@ fn parse_swap_sources(input: &str) -> Result, &'static str> { Ok(sources) } +#[cfg(target_os = "linux")] fn node_is_device_or_partition(candidate: &Path, disk: &Path) -> bool { let candidate = candidate.to_string_lossy(); let disk = disk.to_string_lossy(); @@ -1279,6 +1349,7 @@ fn node_is_device_or_partition(candidate: &Path, disk: &Path) -> bool { } } +#[cfg(target_os = "linux")] fn wipe_leading(node: &Path, cancel: &CancellationToken) -> Result<(), HelperError> { let mut file = std::fs::OpenOptions::new().write(true).open(node)?; let zeros = vec![0u8; 1024 * 1024]; @@ -1293,6 +1364,7 @@ fn wipe_leading(node: &Path, cancel: &CancellationToken) -> Result<(), HelperErr Ok(()) } +#[cfg(target_os = "linux")] fn create_partition_table( node: &Path, scheme: PartitionScheme, @@ -1335,6 +1407,7 @@ fn create_partition_table( Ok(()) } +#[cfg(target_os = "linux")] fn first_partition_node(disk: &Path) -> PathBuf { let name = disk.to_string_lossy(); if name.chars().last().is_some_and(|c| c.is_ascii_digit()) { @@ -1344,6 +1417,7 @@ fn first_partition_node(disk: &Path) -> PathBuf { } } +#[cfg(target_os = "linux")] fn wait_for_first_partition( disk: &Path, cancel: &CancellationToken, @@ -1368,6 +1442,7 @@ fn wait_for_first_partition( ))) } +#[cfg(target_os = "linux")] fn reread_partition_table(node: &Path, cancel: &CancellationToken) -> Result<(), HelperError> { let blockdev = find_tool(tools::BLOCKDEV)?; let mut command = Command::new(blockdev); @@ -1381,6 +1456,7 @@ fn reread_partition_table(node: &Path, cancel: &CancellationToken) -> Result<(), Ok(()) } +#[cfg(target_os = "linux")] fn format_partition( part: &Path, format: &FormatSpec, @@ -1444,6 +1520,7 @@ fn format_partition( Ok(()) } +#[cfg(target_os = "linux")] fn add_ext_block_size(cmd: &mut Command, size: Option) -> Result<(), HelperError> { if let Some(size) = size { if !matches!(size, 1024 | 2048 | 4096) { @@ -1456,18 +1533,21 @@ fn add_ext_block_size(cmd: &mut Command, size: Option) -> Result<(), Helper Ok(()) } +#[cfg(target_os = "linux")] #[derive(Debug)] struct WriteReceipt { bytes_written: u64, sha256: [u8; 32], } +#[cfg(target_os = "linux")] struct WriteSource<'a> { file: &'a File, spec: &'a rufust_helper_protocol::SourceSpec, invoking_user: Option<&'a InvokingUser>, } +#[cfg(target_os = "linux")] fn write_image( target: &File, source: WriteSource<'_>, @@ -1632,6 +1712,7 @@ fn write_image( } } +#[cfg(target_os = "linux")] fn read_image_chunk( reader: &mut impl Read, buffer: &mut [u8], @@ -1658,6 +1739,7 @@ fn read_image_chunk( } } +#[cfg(target_os = "linux")] fn set_nonblocking(fd: libc::c_int) -> Result<(), HelperError> { let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) }; if flags < 0 { @@ -1669,6 +1751,7 @@ fn set_nonblocking(fd: libc::c_int) -> Result<(), HelperError> { Ok(()) } +#[cfg(target_os = "linux")] fn finish_image_write( destination: &File, decoder: &mut Option, @@ -1687,6 +1770,7 @@ fn finish_image_write( } } +#[cfg(target_os = "linux")] fn drop_decoder_privileges(command: &mut Command, user: &InvokingUser) { if unsafe { libc::geteuid() } != 0 { return; @@ -1714,6 +1798,7 @@ fn drop_decoder_privileges(command: &mut Command, user: &InvokingUser) { } } +#[cfg(target_os = "linux")] fn decompressor_for(path: &Path) -> Result<(&'static str, Vec<&'static str>), HelperError> { let extension = path .extension() @@ -1732,6 +1817,7 @@ fn decompressor_for(path: &Path) -> Result<(&'static str, Vec<&'static str>), He } } +#[cfg(target_os = "linux")] fn verify_device_hash( device: &Path, size: u64, @@ -1763,6 +1849,7 @@ fn verify_device_hash( Ok(()) } +#[cfg(target_os = "linux")] fn flush_device(node: &Path, cancel: &CancellationToken) -> Result<(), HelperError> { let blockdev = find_tool(tools::BLOCKDEV)?; let mut command = Command::new(blockdev); @@ -1776,6 +1863,7 @@ fn flush_device(node: &Path, cancel: &CancellationToken) -> Result<(), HelperErr Ok(()) } +#[cfg(target_os = "linux")] fn run_badblocks(node: &Path, cancel: &CancellationToken) -> Result<(), HelperError> { let badblocks = find_tool(tools::BADBLOCKS)?; let mut command = Command::new(badblocks); @@ -1817,7 +1905,11 @@ pub fn sample_dry_request(target_node: PathBuf) -> HelperRequest { node: target_node.clone(), fingerprint: DeviceFingerprint { number: DeviceNumber::new(0, 0), - canonical_sysfs_path: PathBuf::from("/sys/devices/virtual/dry-run"), + canonical_sysfs_path: PathBuf::from(if cfg!(windows) { + r"\\?\dry-run" + } else { + "/sys/devices/virtual/dry-run" + }), size_bytes: 8 * 1024 * 1024 * 1024, logical_block_size: 512, serial: Some("DRYRUN".into()), @@ -1851,7 +1943,7 @@ pub fn write_event_line(out: &mut impl Write, event: &HelperEvent) -> Result<(), Ok(()) } -#[cfg(test)] +#[cfg(all(test, target_os = "linux"))] mod tests { use super::*; use rufust_core::device::{DeviceFingerprint, DeviceNumber}; diff --git a/crates/rufust-helper/src/main.rs b/crates/rufust-helper/src/main.rs index 39ed97c..53ab093 100644 --- a/crates/rufust-helper/src/main.rs +++ b/crates/rufust-helper/src/main.rs @@ -1,6 +1,8 @@ -//! `rufust-helper` — root-only raw-device operations. +//! `rufust-helper` — privileged raw-device operations. //! -//! Invoked via polkit. Never run the desktop GUI as root. +//! On Linux it is invoked via polkit; never run the desktop GUI as root. On +//! Windows, the desktop starts an elevated worker itself; this program offers +//! the same request validation, dry run, and `--execute-pipe` entry point. use std::env; use std::io::{self, BufRead, Read}; @@ -8,6 +10,7 @@ use std::process::ExitCode; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread; +#[cfg(unix)] use std::time::Duration; use rufust_core::progress::CancellationToken; @@ -19,8 +22,10 @@ use rufust_helper_protocol::{ decode_line, HelperEvent, HelperRequest, HelperResult, MAX_MESSAGE_BYTES, }; +#[cfg(unix)] static TERMINATION_REQUESTED: AtomicBool = AtomicBool::new(false); +#[cfg(unix)] extern "C" fn handle_termination_signal(_signal: libc::c_int) { TERMINATION_REQUESTED.store(true, Ordering::Release); } @@ -39,6 +44,16 @@ impl Drop for SignalWatcher { } } +/// Windows consoles have no SIGTERM; the desktop cancels through its pipe. +#[cfg(windows)] +fn watch_termination_signals(_cancel: CancellationToken) -> io::Result { + Ok(SignalWatcher { + stop: Arc::new(AtomicBool::new(false)), + thread: None, + }) +} + +#[cfg(unix)] fn watch_termination_signals(cancel: CancellationToken) -> io::Result { TERMINATION_REQUESTED.store(false, Ordering::Release); let mut action = unsafe { std::mem::zeroed::() }; @@ -83,7 +98,12 @@ fn main() -> ExitCode { } Some("--dry-run") => { // Safe smoke path: validate + emit stages without raw I/O. - let target = args.next().unwrap_or_else(|| "/dev/null".into()); + let default_target = if cfg!(windows) { + r"\\.\PhysicalDrive0" + } else { + "/dev/null" + }; + let target = args.next().unwrap_or_else(|| default_target.into()); let request = sample_dry_request(target.into()); run_request(request, true) } @@ -122,6 +142,14 @@ fn main() -> ExitCode { } } } + #[cfg(windows)] + Some("--execute-pipe") => match args.next() { + Some(name) => ExitCode::from(rufust_helper::serve_pipe(&name)), + None => { + print_help(); + ExitCode::from(2) + } + }, Some("--execute-json") => { let input = match read_stdin_request() { Ok(input) => input, @@ -237,6 +265,7 @@ Usage: rufust-helper --validate-json [FILE] rufust-helper --execute-json # NDJSON HelperRequest on stdin rufust-helper # same as --execute-json (polkit path) + rufust-helper --execute-pipe NAME # Windows: serve the desktop's pipes (elevated) " ); } diff --git a/crates/rufust-helper/src/udisks_engine.rs b/crates/rufust-helper/src/udisks_engine.rs index c23fa60..3280257 100644 --- a/crates/rufust-helper/src/udisks_engine.rs +++ b/crates/rufust-helper/src/udisks_engine.rs @@ -15,11 +15,10 @@ use rufust_helper_protocol::WindowsCustomization; use rufust_image::isofs; use super::*; +use crate::engine::{customization_plan, Meter, Reporter, MIB}; use crate::udisks::{ObjectPath, Udisks}; -use crate::unattend; use crate::windows_media::{self as winmedia, Span}; -const MIB: u64 = 1024 * 1024; const GPT_LINUX_DATA: &str = "0fc63daf-8483-4772-8e79-3d69d8477de4"; /// Version of the reachable udisks2 daemon, or why it cannot be used. @@ -191,86 +190,6 @@ fn table_kind(scheme: PartitionScheme) -> &'static str { } } -/// Stage and byte progress for one job. -struct Reporter<'a> { - job_id: JobId, - sink: &'a mut EventSink, - step: u64, - total: u64, -} - -impl Reporter<'_> { - fn stage(&mut self, stage: ProgressStage, detail: &str) { - let event = progress( - self.job_id, - stage, - self.step, - Some(self.total), - Some(detail.to_owned()), - ); - emit(self.sink, event); - self.step = (self.step + 1).min(self.total); - } - - fn log(&mut self, line: impl Into) { - let event = HelperEvent::Log { - job_id: self.job_id, - line: line.into(), - }; - emit(self.sink, event); - } - - fn bytes(&mut self, stage: ProgressStage, meter: &mut Meter, done: u64, detail: &str) { - if !meter.due(done) { - return; - } - let event = HelperEvent::Progress { - job_id: self.job_id, - stage, - unit: ProgressUnit::Bytes, - completed: done, - total: Some(meter.total), - bytes_per_second: Some(meter.rate(done)), - detail: Some(detail.to_owned()), - cancellability: Cancellability::Immediate, - }; - emit(self.sink, event); - } -} - -struct Meter { - total: u64, - started: Instant, - last: Option, -} - -impl Meter { - fn new(total: u64) -> Self { - Self { - total, - started: Instant::now(), - last: None, - } - } - - fn due(&mut self, done: u64) -> bool { - let now = Instant::now(); - if done < self.total - && self - .last - .is_some_and(|last| now.duration_since(last) < Duration::from_millis(200)) - { - return false; - } - self.last = Some(now); - true - } - - fn rate(&self, done: u64) -> u64 { - (done as f64 / self.started.elapsed().as_secs_f64().max(0.001)) as u64 - } -} - /// Unmounts through udisks2 when dropped, so failures never leave the /// target mounted. struct Mounted<'a> { @@ -736,45 +655,6 @@ struct WindowsMediaOptions<'a> { customization: Option<&'a WindowsCustomization>, } -/// Read the image's Windows details and refuse customization it cannot take. -fn customization_plan( - iso: &mut File, - listing: &isofs::IsoListing, - options: &WindowsCustomization, -) -> Result<(unattend::AnswerFile, u32), HelperError> { - let windows = rufust_image::windows::inspect(iso, listing) - .filter(|windows| windows.is_windows_10_or_later()) - .ok_or_else(|| { - HelperError::Operation( - "Windows User Experience options need Windows 10 or later media".into(), - ) - })?; - if windows.has_panther_unattend || listing.has_file(unattend::ROOT_ANSWER_FILE) { - return Err(HelperError::Operation( - "this image already has its own answer file".into(), - )); - } - if let Some(index) = options.silent_install_index { - if !windows - .editions - .iter() - .any(|edition| edition.index == index) - { - return Err(HelperError::Operation(format!( - "this image has no Windows edition {index}" - ))); - } - } - let arch = windows.arch.ok_or_else(|| { - HelperError::Operation("the Windows architecture of this image is unknown".into()) - })?; - let language = windows.setup_language.as_deref().unwrap_or("en-US"); - Ok(( - unattend::answer_file(options, arch, language), - windows.build, - )) -} - fn write_windows_media( target: &Target<'_>, source: &File, diff --git a/crates/rufust-helper/src/windows/disk.rs b/crates/rufust-helper/src/windows/disk.rs new file mode 100644 index 0000000..1bfebcc --- /dev/null +++ b/crates/rufust-helper/src/windows/disk.rs @@ -0,0 +1,516 @@ +//! Raw disk and volume access for the elevated Windows engine. +//! +//! Windows refuses writes to sectors of a mounted volume, so every volume on +//! the target is locked and dismounted before raw I/O and stays locked until +//! the write is done. Partitions are laid out with the disk IOCTLs, and new +//! volumes are found by their extent on the target disk, never by letter. + +use std::fs::{File, OpenOptions}; +use std::io; +use std::os::windows::fs::{FileExt, OpenOptionsExt}; +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use rufust_core::plan::PartitionScheme; +use rufust_core::progress::CancellationToken; +use rufust_platform::windows::{self as platform, ioctl, wide, Volume}; +use windows_sys::core::GUID; +use windows_sys::Win32::Storage::FileSystem::{ + DeleteVolumeMountPointW, GetLogicalDrives, SetVolumeMountPointW, FILE_FLAG_WRITE_THROUGH, + FILE_SHARE_READ, FILE_SHARE_WRITE, +}; +use windows_sys::Win32::System::Com::CoCreateGuid; +use windows_sys::Win32::System::Ioctl::{ + CREATE_DISK, CREATE_DISK_0, CREATE_DISK_GPT, CREATE_DISK_MBR, DRIVE_LAYOUT_INFORMATION_EX_0, + DRIVE_LAYOUT_INFORMATION_GPT, DRIVE_LAYOUT_INFORMATION_MBR, FSCTL_ALLOW_EXTENDED_DASD_IO, + FSCTL_DISMOUNT_VOLUME, FSCTL_LOCK_VOLUME, FSCTL_UNLOCK_VOLUME, IOCTL_DISK_CREATE_DISK, + IOCTL_DISK_SET_DRIVE_LAYOUT_EX, IOCTL_DISK_UPDATE_PROPERTIES, PARTITION_INFORMATION_EX, + PARTITION_INFORMATION_EX_0, PARTITION_INFORMATION_GPT, PARTITION_INFORMATION_MBR, + PARTITION_STYLE_GPT, PARTITION_STYLE_MBR, PARTITION_STYLE_RAW, +}; + +use crate::{check_cancel, HelperError}; + +pub(crate) const MIB: u64 = 1024 * 1024; +/// Every raw transfer is a multiple of this, and buffers are aligned to it. +const ALIGNMENT: usize = 4096; + +/// A heap buffer whose start is aligned for unbuffered device I/O. +pub(crate) struct AlignedBuffer { + storage: Vec, + start: usize, + len: usize, +} + +impl AlignedBuffer { + pub(crate) fn new(len: usize) -> Self { + let storage = vec![0u8; len + ALIGNMENT]; + let start = storage.as_ptr().align_offset(ALIGNMENT); + Self { + storage, + start, + len, + } + } + + pub(crate) fn as_slice(&self) -> &[u8] { + &self.storage[self.start..self.start + self.len] + } + + pub(crate) fn as_mut_slice(&mut self) -> &mut [u8] { + &mut self.storage[self.start..self.start + self.len] + } +} + +fn open_rw(path: &str) -> io::Result { + OpenOptions::new() + .read(true) + .write(true) + .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE) + .custom_flags(FILE_FLAG_WRITE_THROUGH) + .open(path) +} + +fn write_all_at(file: &File, mut offset: u64, mut bytes: &[u8]) -> io::Result<()> { + while !bytes.is_empty() { + let written = file.seek_write(bytes, offset)?; + if written == 0 { + return Err(io::Error::new( + io::ErrorKind::WriteZero, + "the device accepted no more data", + )); + } + bytes = &bytes[written..]; + offset += written as u64; + } + Ok(()) +} + +fn read_exact_at(file: &File, mut offset: u64, mut buffer: &mut [u8]) -> io::Result<()> { + while !buffer.is_empty() { + let read = file.seek_read(buffer, offset)?; + if read == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "the device ended early", + )); + } + buffer = &mut buffer[read..]; + offset += read as u64; + } + Ok(()) +} + +/// The whole target disk, opened read-write. +pub(crate) struct Disk { + file: File, + pub number: u32, + pub size: u64, + pub sector: u32, +} + +impl Disk { + pub(crate) fn open(number: u32, size: u64, sector: u32) -> Result { + let path = platform::physical_drive_path(number); + let file = open_rw(&path.to_string_lossy()).map_err(|error| { + HelperError::Operation(format!("could not open {}: {error}", path.display())) + })?; + Ok(Self { + file, + number, + size, + sector, + }) + } + + pub(crate) fn write_at(&self, offset: u64, bytes: &[u8]) -> Result<(), HelperError> { + write_all_at(&self.file, offset, bytes).map_err(|error| { + HelperError::Operation(format!("write failed at byte {offset}: {error}")) + }) + } + + pub(crate) fn read_at(&self, offset: u64, buffer: &mut [u8]) -> Result<(), HelperError> { + read_exact_at(&self.file, offset, buffer).map_err(|error| { + HelperError::Operation(format!("read failed at byte {offset}: {error}")) + }) + } + + pub(crate) fn flush(&self) -> Result<(), HelperError> { + self.file.sync_all()?; + Ok(()) + } + + /// Ask Windows to re-read the partition table. + pub(crate) fn rescan(&self) { + let _ = ioctl(&self.file, IOCTL_DISK_UPDATE_PROPERTIES, &[], &mut []); + } + + /// Zero the first and last MiB: old partition tables, the backup GPT, + /// and stale file system signatures. + fn wipe_ends(&self) -> Result<(), HelperError> { + let zeros = AlignedBuffer::new(MIB as usize); + let tail = self.size.saturating_sub(MIB) / u64::from(self.sector) * u64::from(self.sector); + self.write_at(0, zeros.as_slice())?; + let tail_length = (self.size - tail).min(MIB) as usize; + self.write_at(tail, &zeros.as_slice()[..tail_length])?; + self.flush() + } +} + +/// A locked volume. Unlocked when dropped. +pub(crate) struct VolumeLock { + file: File, +} + +impl VolumeLock { + /// Lock and dismount, so the file system can neither use nor later + /// rewrite sectors underneath a raw write. + pub(crate) fn acquire(volume: &Volume) -> Result { + Self::lock(volume, true) + } + + /// Lock but keep the file system mounted, for writing its boot record + /// through this handle as upstream does. + pub(crate) fn acquire_mounted(volume: &Volume) -> Result { + Self::lock(volume, false) + } + + fn lock(volume: &Volume, dismount: bool) -> Result { + let path = volume.device_path(); + let file = open_rw(&path).map_err(|error| { + HelperError::Operation(format!("could not open volume {}: {error}", volume.name)) + })?; + // Explorer and indexers hold handles briefly; retry before forcing. + let mut locked = false; + for attempt in 0..20 { + if ioctl(&file, FSCTL_LOCK_VOLUME, &[], &mut []).is_ok() { + locked = true; + break; + } + if attempt == 9 { + // A forced dismount invalidates other handles; then lock. + let _ = ioctl(&file, FSCTL_DISMOUNT_VOLUME, &[], &mut []); + } + std::thread::sleep(Duration::from_millis(150)); + } + if !locked { + return Err(HelperError::Operation(format!( + "volume {} is in use; close programs that use the drive and try again", + mount_label(volume) + ))); + } + if dismount { + ioctl(&file, FSCTL_DISMOUNT_VOLUME, &[], &mut []).map_err(|error| { + HelperError::Operation(format!( + "could not dismount {}: {error}", + mount_label(volume) + )) + })?; + } + // Raw I/O must not be bounded by the file system's idea of its size. + let _ = ioctl(&file, FSCTL_ALLOW_EXTENDED_DASD_IO, &[], &mut []); + Ok(Self { file }) + } + + pub(crate) fn write_at(&self, offset: u64, bytes: &[u8]) -> io::Result<()> { + write_all_at(&self.file, offset, bytes) + } + + pub(crate) fn read_at(&self, offset: u64, buffer: &mut [u8]) -> io::Result<()> { + read_exact_at(&self.file, offset, buffer) + } + + pub(crate) fn flush(&self) -> io::Result<()> { + self.file.sync_all() + } +} + +impl Drop for VolumeLock { + fn drop(&mut self) { + let _ = self.file.sync_all(); + let _ = ioctl(&self.file, FSCTL_UNLOCK_VOLUME, &[], &mut []); + } +} + +fn mount_label(volume: &Volume) -> String { + volume + .mount_points + .first() + .map(|mount| mount.display().to_string()) + .unwrap_or_else(|| volume.name.clone()) +} + +/// Lock and dismount every volume on `disk`. +pub(crate) fn lock_disk_volumes(disk: u32) -> Result, HelperError> { + platform::volumes() + .iter() + .filter(|volume| volume.on_disk(disk)) + .map(VolumeLock::acquire) + .collect() +} + +/// Flush a mounted volume's file system to the device. +pub(crate) fn flush_volume(volume: &Volume) -> Result<(), HelperError> { + open_rw(&volume.device_path()) + .and_then(|file| file.sync_all()) + .map_err(|error| HelperError::Operation(format!("could not flush the volume: {error}"))) +} + +/// Dismount a volume so the next access reads the device, not the cache. +pub(crate) fn cycle_volume(volume: &Volume) -> Result<(), HelperError> { + drop(VolumeLock::acquire(volume)?); + Ok(()) +} + +/// Wait for the volume that starts at `offset` on `disk` to appear. +pub(crate) fn wait_for_volume( + disk: u32, + offset: u64, + cancel: &CancellationToken, +) -> Result { + let deadline = Instant::now() + Duration::from_secs(20); + loop { + check_cancel(cancel)?; + if let Some(volume) = platform::volumes().into_iter().find(|volume| { + volume.extents.len() == 1 && volume.on_disk(disk) && volume.extents[0].offset == offset + }) { + return Ok(volume); + } + if Instant::now() >= deadline { + return Err(HelperError::Operation( + "Windows did not create a volume for the new partition".into(), + )); + } + std::thread::sleep(Duration::from_millis(250)); + } +} + +/// Remove a new volume's drive letters so Explorer does not offer to format +/// it mid-operation. Returns the first letter it had. +pub(crate) fn hide_volume(volume: &Volume) -> Option { + for mount in &volume.mount_points { + let name = wide(mount); + // SAFETY: `name` is a NUL-terminated mount point path. + unsafe { DeleteVolumeMountPointW(name.as_ptr()) }; + } + volume.mount_points.first().cloned() +} + +/// Give the finished volume a drive letter: `preferred` if free, else the +/// first free letter from D:. +pub(crate) fn show_volume(volume: &Volume, preferred: Option) { + let current = platform::volumes() + .into_iter() + .find(|candidate| candidate.name == volume.name); + if current.is_some_and(|current| !current.mount_points.is_empty()) { + return; + } + // SAFETY: no arguments; returns the bitmask of used letters. + let used = unsafe { GetLogicalDrives() }; + let free = |letter: u8| used & (1 << (letter - b'A')) == 0; + let preferred = preferred + .and_then(|path| path.to_str().and_then(|text| text.bytes().next())) + .map(|letter| letter.to_ascii_uppercase()) + .filter(|letter| letter.is_ascii_uppercase() && free(*letter)); + let Some(letter) = preferred.or_else(|| (b'D'..=b'Z').find(|letter| free(*letter))) else { + return; + }; + let mount = wide(format!("{}:\\", letter as char)); + let name = wide(&volume.name); + // SAFETY: both strings are NUL-terminated. + unsafe { SetVolumeMountPointW(mount.as_ptr(), name.as_ptr()) }; +} + +/// One partition to create. +#[derive(Clone)] +pub(crate) struct PartitionSpec { + pub offset: u64, + pub size: u64, + pub mbr_type: u8, + pub gpt_type: GUID, + pub gpt_name: &'static str, + pub gpt_attributes: u64, + pub active: bool, +} + +pub(crate) const GPT_BASIC_DATA: GUID = GUID::from_u128(0xebd0a0a2_b9e5_4433_87c0_68b6b72699c7); + +fn new_guid() -> Result { + let mut guid = GUID::from_u128(0); + // SAFETY: writes one GUID. + let status = unsafe { CoCreateGuid(&mut guid) }; + if status != 0 { + return Err(HelperError::Operation("could not create a GUID".into())); + } + Ok(guid) +} + +/// DRIVE_LAYOUT_INFORMATION_EX with room for four entries. +#[repr(C)] +struct DriveLayout { + style: u32, + count: u32, + table: DRIVE_LAYOUT_INFORMATION_EX_0, + entries: [PARTITION_INFORMATION_EX; 4], +} + +fn bytes_of(value: &T) -> &[u8] { + // SAFETY: plain-old-data Win32 structures are read as their bytes. + unsafe { std::slice::from_raw_parts((value as *const T).cast::(), size_of::()) } +} + +/// Replace the partition table: wipe both ends, create an empty MBR, GPT, or +/// raw (super-floppy) disk, then add `partitions` and let Windows re-read it. +pub(crate) fn create_layout( + disk: &Disk, + scheme: PartitionScheme, + partitions: &[PartitionSpec], +) -> Result<(), HelperError> { + if partitions.len() > 4 { + return Err(HelperError::Operation("too many partitions".into())); + } + disk.wipe_ends()?; + let handle = &disk.file; + let fail = |step: &str, error: io::Error| { + HelperError::Operation(format!("could not {step} the partition table: {error}")) + }; + let style = match scheme { + PartitionScheme::Mbr => PARTITION_STYLE_MBR, + PartitionScheme::Gpt => PARTITION_STYLE_GPT, + PartitionScheme::SuperFloppy => PARTITION_STYLE_RAW, + }; + let signature = new_guid()?; + let create = CREATE_DISK { + PartitionStyle: style, + Anonymous: if scheme == PartitionScheme::Gpt { + CREATE_DISK_0 { + Gpt: CREATE_DISK_GPT { + DiskId: signature, + MaxPartitionCount: 128, + }, + } + } else { + CREATE_DISK_0 { + Mbr: CREATE_DISK_MBR { + Signature: signature.data1, + }, + } + }, + }; + ioctl(handle, IOCTL_DISK_CREATE_DISK, bytes_of(&create), &mut []) + .map_err(|e| fail("create", e))?; + disk.rescan(); + if scheme == PartitionScheme::SuperFloppy { + return Ok(()); + } + + let sector = u64::from(disk.sector); + // SAFETY: an all-zero PARTITION_INFORMATION_EX is a valid unused entry. + let mut layout: DriveLayout = unsafe { std::mem::zeroed() }; + layout.style = style as u32; + if scheme == PartitionScheme::Gpt { + layout.count = partitions.len() as u32; + layout.table = DRIVE_LAYOUT_INFORMATION_EX_0 { + Gpt: DRIVE_LAYOUT_INFORMATION_GPT { + DiskId: signature, + StartingUsableOffset: (34 * sector) as i64, + UsableLength: disk.size.saturating_sub(68 * sector) as i64, + MaxPartitionCount: 128, + }, + }; + } else { + // MBR layouts always carry four entries. + layout.count = 4; + layout.table = DRIVE_LAYOUT_INFORMATION_EX_0 { + Mbr: DRIVE_LAYOUT_INFORMATION_MBR { + Signature: signature.data1, + CheckSum: 0, + }, + }; + } + for (index, spec) in partitions.iter().enumerate() { + let entry = &mut layout.entries[index]; + entry.PartitionStyle = style; + entry.StartingOffset = spec.offset as i64; + entry.PartitionLength = spec.size as i64; + entry.PartitionNumber = index as u32 + 1; + entry.RewritePartition = 1; + entry.Anonymous = if scheme == PartitionScheme::Gpt { + let mut name = [0u16; 36]; + for (slot, unit) in name.iter_mut().zip(spec.gpt_name.encode_utf16()) { + *slot = unit; + } + PARTITION_INFORMATION_EX_0 { + Gpt: PARTITION_INFORMATION_GPT { + PartitionType: spec.gpt_type, + PartitionId: new_guid()?, + Attributes: spec.gpt_attributes, + Name: name, + }, + } + } else { + PARTITION_INFORMATION_EX_0 { + Mbr: PARTITION_INFORMATION_MBR { + PartitionType: spec.mbr_type, + BootIndicator: u8::from(spec.active), + RecognizedPartition: 1, + HiddenSectors: u32::try_from(spec.offset / sector).map_err(|_| { + HelperError::Operation("partition start is beyond MBR reach".into()) + })?, + PartitionId: GUID::from_u128(0), + }, + } + }; + } + for entry in layout.entries.iter_mut().skip(partitions.len()) { + entry.PartitionStyle = style; + entry.RewritePartition = 1; + } + let length = if scheme == PartitionScheme::Gpt { + size_of::() - (4 - partitions.len()) * size_of::() + } else { + size_of::() + }; + ioctl( + handle, + IOCTL_DISK_SET_DRIVE_LAYOUT_EX, + &bytes_of(&layout)[..length], + &mut [], + ) + .map_err(|e| fail("write", e))?; + disk.rescan(); + Ok(()) +} + +/// Set the type byte of MBR partition `index` (0-based) in sector 0. +pub(crate) fn set_mbr_type(disk: &Disk, index: usize, kind: u8) -> Result<(), HelperError> { + let mut sector = AlignedBuffer::new(disk.sector as usize); + disk.read_at(0, sector.as_mut_slice())?; + let at = 446 + 16 * index + 4; + sector.as_mut_slice()[at] = kind; + disk.write_at(0, sector.as_slice())?; + disk.flush()?; + disk.rescan(); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn aligned_buffers_are_aligned_and_sized() { + for length in [512, 4096, MIB as usize] { + let mut buffer = AlignedBuffer::new(length); + assert_eq!(buffer.as_slice().len(), length); + assert_eq!(buffer.as_mut_slice().as_ptr() as usize % ALIGNMENT, 0); + } + } + + #[test] + fn drive_layout_matches_the_win32_header() { + // PartitionStyle, PartitionCount, then the 40-byte GPT union. + assert_eq!(std::mem::offset_of!(DriveLayout, entries), 48); + assert_eq!(size_of::(), 144); + } +} diff --git a/crates/rufust-helper/src/windows/format.rs b/crates/rufust-helper/src/windows/format.rs new file mode 100644 index 0000000..c09a575 --- /dev/null +++ b/crates/rufust-helper/src/windows/format.rs @@ -0,0 +1,228 @@ +//! File system creation through Windows' own providers (`fmifs.dll` +//! `FormatEx`), as upstream Rufus does when VDS is not used. + +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::Mutex; + +use rufust_core::plan::FileSystem; +use rufust_core::progress::CancellationToken; +use rufust_platform::windows::wide; +use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; + +use crate::HelperError; + +/// FormatEx callback commands (`FILE_SYSTEM_CALLBACK_COMMAND`). +const FCC_PROGRESS: u32 = 0x00; +const FCC_INCOMPATIBLE_FILE_SYSTEM: u32 = 0x03; +const FCC_ACCESS_DENIED: u32 = 0x06; +const FCC_MEDIA_WRITE_PROTECTED: u32 = 0x07; +const FCC_VOLUME_IN_USE: u32 = 0x08; +const FCC_CANT_QUICK_FORMAT: u32 = 0x09; +const FCC_DONE: u32 = 0x0B; +const FCC_BAD_LABEL: u32 = 0x0C; +const FCC_CLUSTER_SIZE_TOO_SMALL: u32 = 0x10; +const FCC_CLUSTER_SIZE_TOO_BIG: u32 = 0x11; +const FCC_VOLUME_TOO_SMALL: u32 = 0x12; +const FCC_VOLUME_TOO_BIG: u32 = 0x13; +const FCC_NO_MEDIA_IN_DRIVE: u32 = 0x14; +const FCC_DEVICE_NOT_READY: u32 = 0x18; +const FCC_ALIGNMENT_VIOLATION: u32 = 0x24; + +/// `MEDIA_TYPE` values FormatEx accepts. +const REMOVABLE_MEDIA: u32 = 11; +const FIXED_MEDIA: u32 = 12; + +type Callback = unsafe extern "system" fn(command: u32, action: u32, data: *mut u8) -> u8; +type FormatEx = unsafe extern "system" fn( + root: *const u16, + media: u32, + file_system: *const u16, + label: *const u16, + quick: i32, + cluster_size: u32, + callback: Callback, +); + +// FormatEx's callback has no context argument, so one format runs at a time. +static FORMAT_LOCK: Mutex<()> = Mutex::new(()); +static CANCELLED: AtomicBool = AtomicBool::new(false); +static SUCCEEDED: AtomicBool = AtomicBool::new(false); +static FAILURE: AtomicU32 = AtomicU32::new(0); +static PERCENT: AtomicU32 = AtomicU32::new(0); +static CANCEL_TOKEN: Mutex> = Mutex::new(None); + +unsafe extern "system" fn callback(command: u32, _action: u32, data: *mut u8) -> u8 { + let cancelled = CANCEL_TOKEN + .lock() + .ok() + .and_then(|token| token.as_ref().map(CancellationToken::is_requested)) + .unwrap_or(false); + match command { + FCC_PROGRESS if !data.is_null() => { + // SAFETY: FormatEx passes a pointer to the percentage. + PERCENT.store( + unsafe { data.cast::().read_unaligned() }, + Ordering::Relaxed, + ); + } + FCC_DONE if !data.is_null() => { + // SAFETY: FormatEx passes a pointer to a BOOLEAN result. + SUCCEEDED.store(unsafe { *data } != 0, Ordering::Relaxed); + } + FCC_INCOMPATIBLE_FILE_SYSTEM + | FCC_ACCESS_DENIED + | FCC_MEDIA_WRITE_PROTECTED + | FCC_VOLUME_IN_USE + | FCC_CANT_QUICK_FORMAT + | FCC_BAD_LABEL + | FCC_CLUSTER_SIZE_TOO_SMALL + | FCC_CLUSTER_SIZE_TOO_BIG + | FCC_VOLUME_TOO_SMALL + | FCC_VOLUME_TOO_BIG + | FCC_NO_MEDIA_IN_DRIVE + | FCC_DEVICE_NOT_READY + | FCC_ALIGNMENT_VIOLATION => { + FAILURE.store(command, Ordering::Relaxed); + } + _ => {} + } + if cancelled { + CANCELLED.store(true, Ordering::Relaxed); + return 0; + } + 1 +} + +fn failure_reason(command: u32) -> &'static str { + match command { + FCC_INCOMPATIBLE_FILE_SYSTEM => "Windows cannot create this file system here", + FCC_ACCESS_DENIED => "access was denied", + FCC_MEDIA_WRITE_PROTECTED => "the media is write-protected", + FCC_VOLUME_IN_USE => "the volume is in use", + FCC_CANT_QUICK_FORMAT => "this volume cannot be quick formatted", + FCC_BAD_LABEL => "the volume label is not valid for this file system", + FCC_CLUSTER_SIZE_TOO_SMALL => "the cluster size is too small", + FCC_CLUSTER_SIZE_TOO_BIG => "the cluster size is too large", + FCC_VOLUME_TOO_SMALL => "the volume is too small for this file system", + FCC_VOLUME_TOO_BIG => "the volume is too large for this file system", + FCC_NO_MEDIA_IN_DRIVE => "there is no media in the drive", + FCC_DEVICE_NOT_READY => "the device is not ready", + FCC_ALIGNMENT_VIOLATION => "the partition is misaligned", + _ => "the format provider reported an error", + } +} + +/// The name `FormatEx` knows a file system by. +pub(crate) fn provider_name(filesystem: FileSystem) -> Result<&'static str, HelperError> { + Ok(match filesystem { + FileSystem::Fat => "FAT", + FileSystem::Fat32 => "FAT32", + FileSystem::ExFat => "exFAT", + FileSystem::Ntfs => "NTFS", + FileSystem::Udf => "UDF", + FileSystem::Ext2 | FileSystem::Ext3 | FileSystem::Ext4 => { + return Err(HelperError::Operation( + "ext2/3/4 creation is not available on Windows yet".into(), + )) + } + FileSystem::Refs => { + return Err(HelperError::Operation( + "ReFS creation is not available".into(), + )) + } + }) +} + +/// Format `volume` (`\\?\Volume{GUID}\`), reporting percent done. +#[allow(clippy::too_many_arguments)] +pub(crate) fn format_volume( + volume: &str, + filesystem: FileSystem, + label: &str, + cluster_size: Option, + quick: bool, + removable: bool, + cancel: &CancellationToken, + progress: &mut dyn FnMut(u32), +) -> Result<(), HelperError> { + let name = provider_name(filesystem)?; + let _guard = FORMAT_LOCK + .lock() + .map_err(|_| HelperError::Operation("format state was poisoned".into()))?; + let library = wide("fmifs.dll"); + // SAFETY: loads a system library by name; it stays loaded for the process. + let module = unsafe { LoadLibraryW(library.as_ptr()) }; + if module.is_null() { + return Err(HelperError::MissingTool("fmifs.dll".into())); + } + // SAFETY: looks up an exported function by a NUL-terminated name. + let Some(address) = (unsafe { GetProcAddress(module, c"FormatEx".as_ptr().cast()) }) else { + return Err(HelperError::MissingTool("fmifs.dll FormatEx".into())); + }; + // SAFETY: FormatEx has this signature on every supported Windows version. + let format_ex: FormatEx = unsafe { std::mem::transmute(address) }; + + // FormatEx rejects a trailing backslash on the volume name. + let root = wide(volume.trim_end_matches('\\')); + let file_system = wide(name); + let label = wide(label); + CANCELLED.store(false, Ordering::Relaxed); + SUCCEEDED.store(false, Ordering::Relaxed); + FAILURE.store(0, Ordering::Relaxed); + PERCENT.store(0, Ordering::Relaxed); + if let Ok(mut token) = CANCEL_TOKEN.lock() { + *token = Some(cancel.clone()); + } + + let worker = std::thread::scope(|scope| { + let handle = scope.spawn(|| { + // SAFETY: all strings are NUL-terminated and outlive the call. + unsafe { + format_ex( + root.as_ptr(), + if removable { + REMOVABLE_MEDIA + } else { + FIXED_MEDIA + }, + file_system.as_ptr(), + label.as_ptr(), + i32::from(quick), + // 0 asks for the default cluster size, which UDF requires. + match filesystem { + FileSystem::Udf => 0, + _ => cluster_size.unwrap_or(0), + }, + callback, + ) + } + }); + let mut last = u32::MAX; + while !handle.is_finished() { + let percent = PERCENT.load(Ordering::Relaxed); + if percent != last { + progress(percent); + last = percent; + } + std::thread::sleep(std::time::Duration::from_millis(100)); + } + handle.join() + }); + if let Ok(mut token) = CANCEL_TOKEN.lock() { + *token = None; + } + if worker.is_err() { + return Err(HelperError::Operation("the format provider crashed".into())); + } + if CANCELLED.load(Ordering::Relaxed) { + return Err(HelperError::Cancelled); + } + if !SUCCEEDED.load(Ordering::Relaxed) { + return Err(HelperError::Operation(format!( + "{name} formatting failed: {}", + failure_reason(FAILURE.load(Ordering::Relaxed)) + ))); + } + progress(100); + Ok(()) +} diff --git a/crates/rufust-helper/src/windows/mod.rs b/crates/rufust-helper/src/windows/mod.rs new file mode 100644 index 0000000..3e281ef --- /dev/null +++ b/crates/rufust-helper/src/windows/mod.rs @@ -0,0 +1,1132 @@ +//! The Windows disk engine. It runs in an elevated copy of the desktop +//! program (or `rufust-helper.exe`) that the unelevated window starts +//! through UAC, and receives one typed request over a private named pipe. +//! +//! The flow mirrors the udisks2 engine: bind and check the source, revalidate +//! the target's identity, lock and dismount its volumes, write, flush, +//! verify. Partitioning uses the disk IOCTLs, file systems come from +//! Windows' own providers (or the built-in large FAT32 formatter), and Windows +//! installer media reuses the shared layout, copy, customization, and boot +//! record code. + +mod disk; +mod format; +mod pipe; +mod source; +#[cfg(test)] +mod vhd_tests; + +use std::fs::File; +use std::io::{self, Read, Seek, SeekFrom}; +use std::path::{Path, PathBuf}; +use std::ptr; +use std::time::{Duration, Instant}; + +use rufust_core::device::DeviceRisk; +use rufust_core::plan::{ + BootMode, FileSystem, ImageSourceKind, PartitionScheme, VerificationLevel, WriteMode, +}; +use rufust_core::progress::{CancellationToken, ProgressStage}; +use rufust_helper_protocol::{ + FormatSpec, HelperEvent, HelperOperation, HelperRequest, HelperResult, SourceSpec, + TargetIdentity, WindowsCustomization, +}; +use rufust_image::isofs; +use rufust_platform::windows::{self as platform, wide, Volume}; +use rufust_platform::{discover_devices, DeviceIdentity}; +use sha2::{Digest, Sha256}; +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; +use windows_sys::Win32::Security::{ + GetTokenInformation, TokenElevation, TOKEN_ELEVATION, TOKEN_QUERY, +}; +use windows_sys::Win32::Storage::FileSystem::SetVolumeLabelW; +use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; + +use crate::engine::{customization_plan, Meter, Reporter, MIB}; +use crate::windows_media::{self as winmedia, Span}; +use crate::{check_cancel, emit, fat32, hex_lower, EventSink, ExecutionOptions, HelperError}; +use disk::{AlignedBuffer, Disk, PartitionSpec, VolumeLock, GPT_BASIC_DATA}; + +pub use pipe::serve_pipe; + +const GIB: u64 = 1024 * MIB; +/// Windows' own formatter stops at 32 GB for FAT32, as upstream notes. +const LARGE_FAT32: u64 = 32 * GIB; + +/// Whether this process holds an elevated (administrator) token. +pub fn is_elevated() -> bool { + let mut token: HANDLE = ptr::null_mut(); + // SAFETY: queries this process's own token. + if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 { + return false; + } + let mut elevation = TOKEN_ELEVATION { TokenIsElevated: 0 }; + let mut length = 0u32; + // SAFETY: `elevation` is writable for its size. + let ok = unsafe { + GetTokenInformation( + token, + TokenElevation, + (&mut elevation as *mut TOKEN_ELEVATION).cast(), + size_of::() as u32, + &mut length, + ) + }; + // SAFETY: closes the token opened above. + unsafe { CloseHandle(token) }; + ok != 0 && elevation.TokenIsElevated != 0 +} + +/// Validate a request for this engine without touching the target. +pub fn validate_request(request: &HelperRequest) -> Result<(), HelperError> { + request.validate()?; + platform::disk_number(&request.target.node).ok_or_else(|| { + HelperError::Operation("the target is not a \\\\.\\PhysicalDrive device".into()) + })?; + match &request.operation { + HelperOperation::WriteMedia { + write_mode, + source, + format, + install_bootloader, + windows_customization, + .. + } => { + if windows_customization.is_some() && *write_mode != WriteMode::IsoFileCopy { + return Err(HelperError::Operation( + "Windows customization needs Windows installer media".into(), + )); + } + if install_bootloader.is_some() || format.persistence_bytes != 0 { + return Err(HelperError::Operation( + "bootloader and persistence operations are not enabled".into(), + )); + } + match write_mode { + WriteMode::DdImage => match source.kind { + ImageSourceKind::Raw + | ImageSourceKind::IsoHybrid + | ImageSourceKind::Vhd + | ImageSourceKind::Vhdx => {} + ImageSourceKind::CompressedRaw => { + source::decoder_kind(&source.path)?; + } + _ => { + return Err(HelperError::Operation( + "source kind cannot be safely raw-written".into(), + )) + } + }, + WriteMode::IsoFileCopy => { + if source.kind != ImageSourceKind::Iso { + return Err(HelperError::Operation( + "file-copy media needs an ISO image".into(), + )); + } + winmedia::requirements(format.filesystem, format.scheme, format.boot_mode)?; + format::provider_name(format.filesystem)?; + } + _ => { + return Err(HelperError::Operation( + "this write mode is not available yet".into(), + )) + } + } + } + HelperOperation::FormatMedia { format, .. } => { + format::provider_name(format.filesystem)?; + } + HelperOperation::CaptureImage { .. } => { + return Err(HelperError::Operation( + "image capture is not available yet".into(), + )) + } + } + Ok(()) +} + +/// Re-resolve the target and compare its identity strictly. +pub fn revalidate_target(expected: &TargetIdentity) -> Result { + let observed = discover_devices(true)? + .into_iter() + .find(|device| device.node == expected.node) + .ok_or_else(|| { + HelperError::Revalidation(format!( + "device {} no longer present", + expected.node.display() + )) + })?; + let fingerprint = &expected.fingerprint; + let serial = fingerprint.serial.as_deref().unwrap_or_default(); + let mismatch = if observed.minor != fingerprint.number.minor + || observed.major != fingerprint.number.major + { + Some("disk number mismatch") + } else if observed.sysfs_path != fingerprint.canonical_sysfs_path { + Some("device interface mismatch") + } else if observed.size_bytes != fingerprint.size_bytes { + Some("device size changed") + } else if observed.logical_sector_size != fingerprint.logical_block_size { + Some("logical sector size changed") + } else if expected.serial != serial { + Some("request contains inconsistent serial identity") + } else if observed.serial != serial { + Some("device serial mismatch") + } else if observed.model != expected.model { + Some("device model mismatch") + } else if observed.read_only { + Some("device is read-only") + } else { + None + }; + if let Some(reason) = mismatch { + return Err(HelperError::Revalidation(reason.into())); + } + let block = platform::to_block_device(&observed, &platform::volumes()); + for risk in [ + DeviceRisk::ContainsRoot, + DeviceRisk::ContainsBoot, + DeviceRisk::ContainsSwap, + DeviceRisk::ActiveRaidMember, + DeviceRisk::ActiveVolumeMember, + DeviceRisk::ReadOnly, + DeviceRisk::HasDependents, + DeviceRisk::IdentityUnstable, + ] { + if block.has_risk(risk) { + return Err(HelperError::Revalidation(format!( + "target has blocking risk: {risk:?}" + ))); + } + } + Ok(observed) +} + +/// Inspect virtual capacity without elevation, for the desktop preview. +pub fn inspect_virtual_disk_for_user( + source: &File, + kind: ImageSourceKind, + cancel: &CancellationToken, +) -> Result { + check_cancel(cancel)?; + if !source.metadata()?.is_file() { + return Err(HelperError::Operation( + "virtual disk inspection requires a regular file".into(), + )); + } + let path = source::final_path(source) + .ok_or_else(|| HelperError::Operation("the image path could not be resolved".into()))?; + source::virtual_size(&path, kind) +} + +/// Execute a validated request. Writing needs an elevated process. +pub fn execute( + mut request: HelperRequest, + options: ExecutionOptions, + mut sink: EventSink, +) -> Result { + validate_request(&request)?; + if options.dry_run { + emit( + &mut sink, + HelperEvent::Accepted { + job_id: request.job_id, + }, + ); + emit( + &mut sink, + HelperEvent::Log { + job_id: request.job_id, + line: "Dry run: the request is valid; nothing was written.".into(), + }, + ); + let result = HelperResult::Success; + emit( + &mut sink, + HelperEvent::Finished { + job_id: request.job_id, + result: result.clone(), + }, + ); + return Ok(result); + } + if !is_elevated() { + return Err(HelperError::Operation( + "writing to disks needs administrator rights".into(), + )); + } + let cancel = options.cancel.clone(); + let source_file = match &request.operation { + HelperOperation::WriteMedia { source, .. } => Some(source::bind(source)?), + _ => None, + }; + if let HelperOperation::WriteMedia { source, .. } = &mut request.operation { + if matches!(source.kind, ImageSourceKind::Vhd | ImageSourceKind::Vhdx) { + let size = source::virtual_size(&source.path, source.kind)?; + if source + .decompressed_size_bytes + .is_some_and(|expected| expected != size) + { + return Err(HelperError::Operation( + "virtual disk size changed since selection".into(), + )); + } + source.decompressed_size_bytes = Some(size); + } + } + + emit( + &mut sink, + HelperEvent::Accepted { + job_id: request.job_id, + }, + ); + let mut report = Reporter { + job_id: request.job_id, + sink: &mut sink, + step: 0, + total: 9, + }; + report.log(format!( + "Using the Windows disk engine (Rufust {})", + crate::HELPER_VERSION + )); + report.stage(ProgressStage::Preparing, "Checking the target device"); + let identity = revalidate_target(&request.target)?; + if let (HelperOperation::WriteMedia { source, .. }, Some(file)) = + (&request.operation, source_file.as_ref()) + { + let on_target = source::volume_of(file) + .map(|volume| { + platform::volumes() + .iter() + .any(|candidate| candidate.name == volume && candidate.on_disk(identity.minor)) + }) + .unwrap_or(false); + if on_target { + return Err(HelperError::Revalidation( + "source image is stored on the target device".into(), + )); + } + if source.decompressed_size_bytes.unwrap_or(source.size_bytes) > identity.size_bytes { + return Err(HelperError::Operation( + "image is larger than the target device".into(), + )); + } + } + check_cancel(&cancel)?; + + let target = Target { + identity: &identity, + cancel: &cancel, + }; + match &request.operation { + HelperOperation::WriteMedia { + write_mode: WriteMode::DdImage, + source, + verification, + bad_blocks, + .. + } => { + let file = source_file + .as_ref() + .ok_or_else(|| HelperError::Operation("bound source missing".into()))?; + write_disk_image( + &target, + file, + source, + *verification, + *bad_blocks, + &mut report, + )?; + } + HelperOperation::WriteMedia { + format, + verification, + bad_blocks, + windows_customization, + .. + } => { + let file = source_file + .as_ref() + .ok_or_else(|| HelperError::Operation("bound source missing".into()))?; + write_windows_media( + &target, + file, + MediaOptions { + format, + verification: *verification, + bad_blocks: *bad_blocks, + customization: windows_customization + .as_deref() + .filter(|options| !options.is_empty()), + }, + &mut report, + )?; + } + HelperOperation::FormatMedia { format, bad_blocks } => { + format_media(&target, format, *bad_blocks, &mut report)?; + } + HelperOperation::CaptureImage { .. } => { + return Err(HelperError::Operation( + "image capture is not available yet".into(), + )) + } + } + + report.step = report.total; + report.stage(ProgressStage::Finalizing, "Complete"); + let result = HelperResult::Success; + emit( + &mut sink, + HelperEvent::Finished { + job_id: request.job_id, + result: result.clone(), + }, + ); + Ok(result) +} + +struct Target<'a> { + identity: &'a DeviceIdentity, + cancel: &'a CancellationToken, +} + +impl Target<'_> { + fn number(&self) -> u32 { + self.identity.minor + } + + fn sector(&self) -> u64 { + u64::from(self.identity.logical_sector_size.max(512)) + } + + /// Lock every volume on the disk, then open the disk itself. + fn open(&self, report: &mut Reporter<'_>) -> Result<(Vec, Disk), HelperError> { + report.stage(ProgressStage::Unmounting, "Unmounting the target"); + let locks = disk::lock_disk_volumes(self.number())?; + check_cancel(self.cancel)?; + report.stage(ProgressStage::Authorizing, "Opening the device"); + let disk = Disk::open( + self.number(), + self.identity.size_bytes, + self.identity.logical_sector_size.max(512), + )?; + Ok((locks, disk)) + } +} + +fn decode_error(error: io::Error) -> HelperError { + HelperError::Operation(format!( + "the image could not be read or decoded (invalid or truncated input): {error}" + )) +} + +struct WriteReceipt { + bytes_written: u64, + sha256: [u8; 32], +} + +fn write_disk_image( + target: &Target<'_>, + file: &File, + spec: &SourceSpec, + verification: VerificationLevel, + bad_blocks: bool, + report: &mut Reporter<'_>, +) -> Result<(), HelperError> { + let (locks, disk) = target.open(report)?; + if bad_blocks { + test_bad_blocks(&disk, target.cancel, report)?; + } + report.stage(ProgressStage::WritingImage, "Writing the image"); + let mut attached = None; + let (reader, total): (Box, Option) = match spec.kind { + ImageSourceKind::CompressedRaw => ( + source::decoder(file, &spec.path)?, + spec.decompressed_size_bytes, + ), + ImageSourceKind::Vhd | ImageSourceKind::Vhdx => { + let virtual_disk = source::attach(&spec.path, spec.kind)?; + if spec + .decompressed_size_bytes + .is_some_and(|expected| expected != virtual_disk.size) + { + return Err(HelperError::Operation( + "virtual disk size changed since selection".into(), + )); + } + let size = virtual_disk.size; + let reader = Box::new(virtual_disk.disk.try_clone()?.take(size)); + attached = Some(virtual_disk); + (reader, Some(size)) + } + _ => { + let mut plain = file.try_clone()?; + plain.seek(SeekFrom::Start(0))?; + (Box::new(plain), Some(spec.size_bytes)) + } + }; + let limit = total.unwrap_or(disk.size).min(disk.size); + let receipt = copy_to_disk( + &disk, + reader, + limit, + total, + &spec.path, + target.cancel, + report, + )?; + drop(attached); + if matches!(spec.kind, ImageSourceKind::Raw | ImageSourceKind::IsoHybrid) + && receipt.bytes_written != spec.size_bytes + { + return Err(HelperError::Operation( + "source image changed while it was being read".into(), + )); + } + if let Some(expected) = total { + if receipt.bytes_written != expected { + return Err(HelperError::Operation(format!( + "decoded size mismatch: expected {expected}, wrote {}", + receipt.bytes_written + ))); + } + } + if let Some(expected) = &spec.expected_sha256 { + if hex_lower(&receipt.sha256) != expected.to_ascii_lowercase() { + return Err(HelperError::Operation( + "source SHA-256 did not match the expected value".into(), + )); + } + } + report.stage(ProgressStage::Syncing, "Flushing"); + disk.flush()?; + if verification == VerificationLevel::FullReadback { + report.stage(ProgressStage::Verifying, "Reading the device back"); + verify_disk( + &disk, + receipt.bytes_written, + &receipt.sha256, + target.cancel, + report, + )?; + } + drop(locks); + disk.rescan(); + Ok(()) +} + +fn copy_to_disk( + disk: &Disk, + mut reader: Box, + limit: u64, + total: Option, + path: &Path, + cancel: &CancellationToken, + report: &mut Reporter<'_>, +) -> Result { + let chunk = MIB as usize; + let sector = disk.sector as usize; + let mut buffer = AlignedBuffer::new(chunk); + let mut hasher = Sha256::new(); + let mut written = 0u64; + let mut meter = Meter::new(total.unwrap_or(0)); + let detail = format!("Writing {}", path.display()); + loop { + check_cancel(cancel)?; + let bytes = buffer.as_mut_slice(); + let mut filled = 0; + while filled < chunk { + match reader.read(&mut bytes[filled..]) { + Ok(0) => break, + Ok(count) => filled += count, + Err(error) if error.kind() == io::ErrorKind::Interrupted => {} + Err(error) => return Err(decode_error(error)), + } + } + if filled == 0 { + break; + } + if written + filled as u64 > limit { + return Err(HelperError::Operation( + "decoded image exceeds its declared size or target capacity".into(), + )); + } + hasher.update(&bytes[..filled]); + // Devices take whole sectors; pad the final partial sector. + let padded = filled.div_ceil(sector) * sector; + bytes[filled..padded].fill(0); + disk.write_at(written, &bytes[..padded])?; + written += filled as u64; + if total.is_some() { + report.bytes(ProgressStage::WritingImage, &mut meter, written, &detail); + } + if filled < chunk { + break; + } + } + if written == 0 { + return Err(HelperError::Operation("source image was empty".into())); + } + Ok(WriteReceipt { + bytes_written: written, + sha256: hasher.finalize().into(), + }) +} + +/// Hash the first `size` bytes of the device and compare. +fn verify_disk( + disk: &Disk, + size: u64, + expected: &[u8; 32], + cancel: &CancellationToken, + report: &mut Reporter<'_>, +) -> Result<(), HelperError> { + let chunk = 4 * MIB; + let sector = u64::from(disk.sector); + let mut buffer = AlignedBuffer::new(chunk as usize); + let mut hasher = Sha256::new(); + let mut meter = Meter::new(size); + let mut offset = 0u64; + while offset < size { + check_cancel(cancel)?; + let wanted = (size - offset).min(chunk); + let read = wanted.div_ceil(sector) * sector; + disk.read_at(offset, &mut buffer.as_mut_slice()[..read as usize])?; + hasher.update(&buffer.as_slice()[..wanted as usize]); + offset += wanted; + report.bytes(ProgressStage::Verifying, &mut meter, offset, "Verifying"); + } + let actual: [u8; 32] = hasher.finalize().into(); + if actual != *expected { + return Err(HelperError::Operation( + "verification hash did not match the written image".into(), + )); + } + Ok(()) +} + +/// `badblocks -w`: write each pattern over the device, then read it back. +fn test_bad_blocks( + disk: &Disk, + cancel: &CancellationToken, + report: &mut Reporter<'_>, +) -> Result<(), HelperError> { + const PATTERNS: [u8; 4] = [0xaa, 0x55, 0xff, 0x00]; + let chunk = 4 * MIB; + let size = disk.size; + report.stage(ProgressStage::TestingMedia, "Checking for bad blocks"); + let mut meter = Meter::new(size * 2 * PATTERNS.len() as u64); + let mut done = 0u64; + let mut written = AlignedBuffer::new(chunk as usize); + let mut read = AlignedBuffer::new(chunk as usize); + let mut bad = 0u64; + for pattern in PATTERNS { + written.as_mut_slice().fill(pattern); + let label = format!("Bad-block test: writing 0x{pattern:02x}"); + let mut offset = 0; + while offset < size { + check_cancel(cancel)?; + let length = chunk.min(size - offset) as usize; + disk.write_at(offset, &written.as_slice()[..length])?; + offset += length as u64; + done += length as u64; + report.bytes(ProgressStage::TestingMedia, &mut meter, done, &label); + } + disk.flush()?; + let label = format!("Bad-block test: reading 0x{pattern:02x}"); + let mut offset = 0; + while offset < size { + check_cancel(cancel)?; + let length = chunk.min(size - offset) as usize; + match disk.read_at(offset, &mut read.as_mut_slice()[..length]) { + Ok(()) => { + bad += read.as_slice()[..length] + .chunks(512) + .filter(|sector| sector.iter().any(|byte| *byte != pattern)) + .count() as u64 + } + Err(_) => bad += length as u64 / 512, + } + offset += length as u64; + done += length as u64; + report.bytes(ProgressStage::TestingMedia, &mut meter, done, &label); + } + } + if bad > 0 { + return Err(HelperError::Operation(format!( + "bad-block test found {bad} unreliable sectors; this device should not be used" + ))); + } + report.log("Bad-block test passed."); + Ok(()) +} + +/// The single data partition of a plain formatted drive. +fn data_span(size: u64, sector: u64, scheme: PartitionScheme) -> Result { + if scheme == PartitionScheme::Mbr && size / sector > u64::from(u32::MAX) { + return Err(HelperError::Operation( + "MBR cannot address a disk this large; choose GPT".into(), + )); + } + let tail = if scheme == PartitionScheme::Gpt { + 34 * sector + } else { + 0 + }; + let end = size.saturating_sub(tail) / MIB * MIB; + if end <= 2 * MIB { + return Err(HelperError::Operation("the device is too small".into())); + } + Ok(Span { + offset: MIB, + size: end - MIB, + }) +} + +fn mbr_type(filesystem: FileSystem) -> u8 { + match filesystem { + FileSystem::Fat => 0x0e, + FileSystem::Fat32 => 0x0c, + _ => 0x07, + } +} + +fn partition( + span: Span, + kind: u8, + name: &'static str, + attributes: u64, + active: bool, +) -> PartitionSpec { + PartitionSpec { + offset: span.offset, + size: span.size, + mbr_type: kind, + gpt_type: GPT_BASIC_DATA, + gpt_name: name, + gpt_attributes: attributes, + active, + } +} + +/// The label each file system accepts (FAT and exFAT: 11 upper-case +/// characters), as the desktop already prepared it. +fn label_for(filesystem: FileSystem, label: &str) -> String { + filesystem.volume_label(label) +} + +/// Create the file system on a new, hidden volume. +fn format_filesystem( + volume: &Volume, + span: Span, + format: &FormatSpec, + target: &Target<'_>, + report: &mut Reporter<'_>, +) -> Result<(), HelperError> { + report.stage(ProgressStage::Formatting, format.filesystem.as_str()); + let label = label_for(format.filesystem, &format.label); + if format.filesystem == FileSystem::Fat32 && span.size > LARGE_FAT32 { + let sector = target.sector(); + let layout = fat32::plan(span.size, sector as u32, format.cluster_size)?; + let hidden = u32::try_from(span.offset / sector).unwrap_or(0); + let volume_id = (std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_nanos()) as u32) + | 1; + report.log(format!( + "Large FAT32: {} clusters of {} bytes", + layout.clusters, + layout.sectors_per_cluster * layout.bytes_per_sector + )); + let lock = VolumeLock::acquire(volume)?; + let mut aligned = AlignedBuffer::new(MIB as usize); + fat32::write( + &layout, + hidden, + volume_id, + &label, + target.cancel, + &mut |offset, bytes| { + let staged = &mut aligned.as_mut_slice()[..bytes.len()]; + staged.copy_from_slice(bytes); + lock.write_at(offset, staged) + }, + )?; + lock.flush()?; + drop(lock); + set_label(volume, &label)?; + return Ok(()); + } + let mut meter = Meter::new(span.size); + let detail = format!("Formatting {}", format.filesystem.as_str()); + format::format_volume( + &volume.name, + format.filesystem, + &label, + format.cluster_size, + format.quick_format, + target.identity.removable, + target.cancel, + &mut |percent| { + let done = span.size / 100 * u64::from(percent.min(100)); + report.bytes(ProgressStage::Formatting, &mut meter, done, &detail); + }, + ) +} + +/// Set a label once Windows has mounted the new file system. +fn set_label(volume: &Volume, label: &str) -> Result<(), HelperError> { + let name = wide(&volume.name); + let label = wide(label); + let deadline = Instant::now() + Duration::from_secs(10); + loop { + // SAFETY: both strings are NUL-terminated. + if unsafe { SetVolumeLabelW(name.as_ptr(), label.as_ptr()) } != 0 { + return Ok(()); + } + if Instant::now() >= deadline { + return Err(HelperError::Operation(format!( + "Windows did not mount the new FAT32 volume: {}", + io::Error::last_os_error() + ))); + } + std::thread::sleep(Duration::from_millis(250)); + } +} + +/// The root of a mounted volume, once Windows answers for it. +fn volume_root(volume: &Volume, cancel: &CancellationToken) -> Result { + let root = PathBuf::from(&volume.name); + let deadline = Instant::now() + Duration::from_secs(15); + while std::fs::read_dir(&root).is_err() { + check_cancel(cancel)?; + if Instant::now() >= deadline { + return Err(HelperError::Operation( + "Windows did not mount the formatted volume".into(), + )); + } + std::thread::sleep(Duration::from_millis(250)); + } + Ok(root) +} + +fn format_media( + target: &Target<'_>, + format: &FormatSpec, + bad_blocks: bool, + report: &mut Reporter<'_>, +) -> Result<(), HelperError> { + let (locks, disk) = target.open(report)?; + if bad_blocks { + test_bad_blocks(&disk, target.cancel, report)?; + } + check_cancel(target.cancel)?; + report.stage(ProgressStage::Partitioning, partition_label(format.scheme)); + let span = if format.scheme == PartitionScheme::SuperFloppy { + Span { + offset: 0, + size: disk.size, + } + } else { + data_span(disk.size, target.sector(), format.scheme)? + }; + let partitions = if format.scheme == PartitionScheme::SuperFloppy { + Vec::new() + } else { + vec![partition(span, mbr_type(format.filesystem), "", 0, false)] + }; + disk::create_layout(&disk, format.scheme, &partitions)?; + drop(locks); + let volume = + disk::wait_for_volume(disk.number, span.offset, target.cancel).map_err(|error| { + if format.scheme == PartitionScheme::SuperFloppy { + HelperError::Operation( + "Windows mounts super-floppy volumes only on removable media; choose MBR or GPT" + .into(), + ) + } else { + error + } + })?; + let letter = disk::hide_volume(&volume); + format_filesystem(&volume, span, format, target, report)?; + disk::show_volume(&volume, letter); + Ok(()) +} + +fn partition_label(scheme: PartitionScheme) -> &'static str { + match scheme { + PartitionScheme::Mbr => "MBR", + PartitionScheme::Gpt => "GPT", + PartitionScheme::SuperFloppy => "Super floppy", + } +} + +struct MediaOptions<'a> { + format: &'a FormatSpec, + verification: VerificationLevel, + bad_blocks: bool, + customization: Option<&'a WindowsCustomization>, +} + +fn write_windows_media( + target: &Target<'_>, + source: &File, + options: MediaOptions<'_>, + report: &mut Reporter<'_>, +) -> Result<(), HelperError> { + let MediaOptions { + format, + verification, + bad_blocks, + customization, + } = options; + let cancel = target.cancel; + // Everything that can be checked is checked before the first write. + let needs = winmedia::requirements(format.filesystem, format.scheme, format.boot_mode)?; + let mut iso = source.try_clone()?; + let listing = isofs::list(&mut iso)? + .ok_or_else(|| HelperError::Operation("the ISO file system could not be read".into()))?; + let has = |path: &str| listing.has_file(path); + if !(has("sources/install.wim") || has("sources/install.esd") || has("sources/install.swm")) { + return Err(HelperError::Operation( + "this ISO is not Windows installation media".into(), + )); + } + if needs.bios_boot && !has("bootmgr") { + return Err(HelperError::Operation( + "this image has no BIOS boot manager; choose UEFI".into(), + )); + } + if format.boot_mode != BootMode::Bios + && ![ + "efi/boot/bootx64.efi", + "efi/boot/bootia32.efi", + "efi/boot/bootaa64.efi", + ] + .iter() + .any(|path| has(path)) + { + return Err(HelperError::Operation( + "this image has no UEFI boot loader; choose BIOS".into(), + )); + } + let layout = winmedia::plan_layout( + target.identity.size_bytes, + target.sector(), + format.scheme, + needs.uefi_ntfs, + )?; + winmedia::check_fits(&listing, format.filesystem, layout.data.size)?; + let customization = match customization { + Some(options) => Some((customization_plan(&mut iso, &listing, options)?, options)), + None => None, + }; + report.log(format!( + "Windows media: {} files, {} MiB, {}{}", + listing.entries.iter().filter(|entry| !entry.is_dir).count(), + listing.total_file_bytes() / MIB, + format.filesystem.as_str(), + if needs.uefi_ntfs { " + UEFI:NTFS" } else { "" } + )); + + let (locks, disk) = target.open(report)?; + if bad_blocks { + test_bad_blocks(&disk, cancel, report)?; + } + check_cancel(cancel)?; + + report.stage(ProgressStage::Partitioning, partition_label(format.scheme)); + let gpt = format.scheme == PartitionScheme::Gpt; + let mut partitions = vec![partition( + layout.data, + mbr_type(format.filesystem), + winmedia::MAIN_PARTITION_NAME, + 0, + needs.bios_boot, + )]; + if let Some(span) = layout.uefi_ntfs { + // MBR: FAT12 until the files are in, then 0xEF. + partitions.push(partition( + span, + 0x01, + winmedia::UEFI_NTFS_NAME, + winmedia::GPT_NO_DRIVE_LETTER, + false, + )); + } + disk::create_layout(&disk, format.scheme, &partitions)?; + drop(locks); + let data = disk::wait_for_volume(disk.number, layout.data.offset, cancel)?; + let letter = disk::hide_volume(&data); + let uefi = match layout.uefi_ntfs { + Some(span) => { + let volume = disk::wait_for_volume(disk.number, span.offset, cancel)?; + disk::hide_volume(&volume); + Some(volume) + } + None => None, + }; + check_cancel(cancel)?; + + format_filesystem(&data, layout.data, format, target, report)?; + if let Some(volume) = &uefi { + format::format_volume( + &volume.name, + FileSystem::Fat, + winmedia::UEFI_NTFS_LABEL, + None, + true, + target.identity.removable, + cancel, + &mut |_| {}, + )?; + let root = volume_root(volume, cancel)?; + winmedia::write_uefi_ntfs_files(&root)?; + disk::flush_volume(volume)?; + report.log("Installed the UEFI:NTFS boot partition."); + } + check_cancel(cancel)?; + + report.stage(ProgressStage::ExtractingFiles, "Copying Windows files"); + let root = volume_root(&data, cancel)?; + let total = listing.total_file_bytes(); + let mut meter = Meter::new(total); + let mut copies = { + let mut on_progress = |done: u64, path: &str| { + report.bytes( + ProgressStage::ExtractingFiles, + &mut meter, + done, + &format!("Copying {path}"), + ) + }; + winmedia::copy_listing(&mut iso, &listing, &root, cancel, &mut on_progress)? + }; + if let Some(((answer, build), options)) = &customization { + report.stage( + ProgressStage::ApplyingCustomization, + "Applying Windows customization", + ); + for line in &answer.log { + report.log(line.clone()); + } + winmedia::apply_customization( + &root, + answer, + options.bypass_requirements, + *build, + &mut copies, + &mut |line| report.log(line), + )?; + } + report.stage(ProgressStage::Syncing, "Flushing the copied files"); + disk::flush_volume(&data)?; + check_cancel(cancel)?; + + if needs.bios_boot { + report.stage( + ProgressStage::InstallingBootloader, + "Writing BIOS boot code", + ); + install_bios_boot_code(&disk, &data, layout.data.offset, format.filesystem)?; + report.log("Installed the Windows 7 MBR and the partition boot record."); + } + if uefi.is_some() && !gpt { + disk::set_mbr_type(&disk, 1, 0xef)?; + } + + if verification != VerificationLevel::None { + report.stage(ProgressStage::Verifying, "Reading the copied files back"); + // A dismount drops the cache, so the files are read from the device. + disk::cycle_volume(&data)?; + let root = volume_root(&data, cancel)?; + let mut meter = Meter::new(winmedia::copied_bytes(&copies)); + let mut on_progress = |done: u64| { + report.bytes( + ProgressStage::Verifying, + &mut meter, + done, + "Verifying copied files", + ) + }; + winmedia::verify_copies(&copies, &root, &root, cancel, &mut on_progress)?; + } + disk::show_volume(&data, letter); + Ok(()) +} + +fn install_bios_boot_code( + disk: &Disk, + data: &Volume, + data_offset: u64, + filesystem: FileSystem, +) -> Result<(), HelperError> { + let sector = u64::from(disk.sector); + let mut first = AlignedBuffer::new(sector as usize); + disk.read_at(0, first.as_mut_slice())?; + winmedia::patch_mbr(&mut first.as_mut_slice()[..512])?; + disk.write_at(0, first.as_slice())?; + disk.flush()?; + + let start = u32::try_from(data_offset / sector) + .map_err(|_| HelperError::Operation("partition start is beyond MBR reach".into()))?; + let length = (winmedia::BOOT_AREA_BYTES as u64).div_ceil(sector) * sector; + let lock = VolumeLock::acquire_mounted(data)?; + let mut area = AlignedBuffer::new(length as usize); + lock.read_at(0, area.as_mut_slice())?; + winmedia::patch_boot_record( + &mut area.as_mut_slice()[..winmedia::BOOT_AREA_BYTES], + filesystem, + start, + )?; + lock.write_at(0, area.as_slice())?; + lock.flush()?; + drop(lock); + disk.rescan(); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plain_partitions_leave_room_for_the_backup_gpt() { + let size = 8 * GIB; + let gpt = data_span(size, 512, PartitionScheme::Gpt).expect("gpt span"); + assert_eq!(gpt.offset, MIB); + assert!(gpt.end() <= size - 34 * 512); + assert_eq!(gpt.end() % MIB, 0); + let mbr = data_span(size, 512, PartitionScheme::Mbr).expect("mbr span"); + assert_eq!(mbr.end(), size); + assert!(data_span(MIB, 512, PartitionScheme::Mbr).is_err()); + assert!(data_span(4096 * GIB, 512, PartitionScheme::Mbr).is_err()); + } + + #[test] + fn labels_suit_the_file_system() { + assert_eq!(label_for(FileSystem::Fat32, "Rufust media"), "RUFUST MEDI"); + assert_eq!(label_for(FileSystem::Fat32, ""), ""); + assert_eq!(label_for(FileSystem::Ntfs, "Rufust media"), "Rufust media"); + } + + #[test] + fn requests_need_a_physical_drive_target() { + let mut request = crate::sample_dry_request(PathBuf::from(r"\\.\PhysicalDrive7")); + validate_request(&request).expect("valid dry-run request"); + request.target.node = PathBuf::from(r"C:\image.img"); + assert!(validate_request(&request).is_err()); + } + + #[test] + fn ext_and_capture_requests_are_refused() { + let mut request = crate::sample_dry_request(PathBuf::from(r"\\.\PhysicalDrive7")); + if let HelperOperation::FormatMedia { format, .. } = &mut request.operation { + format.filesystem = FileSystem::Ext4; + } + assert!(validate_request(&request).is_err()); + } +} diff --git a/crates/rufust-helper/src/windows/pipe.rs b/crates/rufust-helper/src/windows/pipe.rs new file mode 100644 index 0000000..f83b8a0 --- /dev/null +++ b/crates/rufust-helper/src/windows/pipe.rs @@ -0,0 +1,116 @@ +//! The elevated side of the desktop's private pipes. +//! +//! The unelevated window creates `\\.\pipe\-control` (it writes) and +//! `\\.\pipe\-events` (it reads), then starts this process through UAC +//! with ``. One NDJSON request arrives on the control pipe; afterwards +//! a `cancel` line or the window closing the pipe requests cancellation. +//! Events, including the terminal result, go back on the events pipe. + +use std::fs::{File, OpenOptions}; +use std::io::{BufRead, BufReader, Read}; +use std::sync::{Arc, Mutex}; + +use rufust_core::progress::CancellationToken; +use rufust_helper_protocol::{ + decode_line, HelperEvent, HelperRequest, HelperResult, MAX_MESSAGE_BYTES, +}; + +use crate::{write_event_line, ExecutionOptions, HelperError}; + +/// Pipe names are generated by the desktop; accept nothing that could +/// reach another path. +fn valid_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 64 + && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') +} + +/// Serve one request from the desktop. Returns the process exit code. +pub fn serve_pipe(name: &str) -> u8 { + if !valid_name(name) { + return 2; + } + let Ok(control) = File::open(format!(r"\\.\pipe\{name}-control")) else { + return 2; + }; + let Ok(events) = OpenOptions::new() + .write(true) + .open(format!(r"\\.\pipe\{name}-events")) + else { + return 2; + }; + let events = Arc::new(Mutex::new(events)); + let mut control = BufReader::new(control); + let mut line = Vec::new(); + let read = (&mut control) + .take((MAX_MESSAGE_BYTES + 1) as u64) + .read_until(b'\n', &mut line); + if read.is_err() || line.len() > MAX_MESSAGE_BYTES { + return 2; + } + let Ok(request) = decode_line::(&line) else { + return 2; + }; + let job_id = request.job_id; + + let cancel = CancellationToken::new(); + let watcher = cancel.clone(); + std::thread::spawn(move || { + let mut command = String::new(); + loop { + command.clear(); + match control.read_line(&mut command) { + Ok(0) | Err(_) => break, + Ok(_) if command.trim() == "cancel" => break, + Ok(_) => {} + } + } + watcher.request(); + }); + + let sink_events = Arc::clone(&events); + let result = crate::execute( + request, + ExecutionOptions { + dry_run: false, + cancel, + }, + Box::new(move |event| { + if let Ok(mut out) = sink_events.lock() { + let _ = write_event_line(&mut *out, &event); + } + }), + ); + match result { + Ok(_) => 0, + Err(error) => { + let result = match error { + HelperError::Cancelled => HelperResult::Cancelled { + message: "Operation cancelled; target media may be incomplete.".into(), + }, + other => HelperResult::Failed { + code: "helper-operation".into(), + message: other.to_string(), + }, + }; + if let Ok(mut out) = events.lock() { + let _ = write_event_line(&mut *out, &HelperEvent::Finished { job_id, result }); + } + 1 + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pipe_names_cannot_escape_the_pipe_namespace() { + assert!(valid_name("rufust-1234-5678")); + assert!(!valid_name("")); + assert!(!valid_name(r"..\..\evil")); + assert!(!valid_name("a/b")); + assert!(!valid_name(&"a".repeat(65))); + } +} diff --git a/crates/rufust-helper/src/windows/source.rs b/crates/rufust-helper/src/windows/source.rs new file mode 100644 index 0000000..037c8ce --- /dev/null +++ b/crates/rufust-helper/src/windows/source.rs @@ -0,0 +1,529 @@ +//! Opening the source image on Windows and turning it into a byte stream: +//! plain files, compressed images decoded in-process by memory-safe Rust +//! decoders, and VHD/VHDX attached read-only through the system's virtual +//! disk service. + +use std::fs::{File, OpenOptions}; +use std::io::{self, BufReader, Read, Seek, SeekFrom}; +use std::os::windows::fs::{MetadataExt, OpenOptionsExt}; +use std::os::windows::io::AsRawHandle; +use std::path::Path; +use std::ptr; + +use rufust_core::plan::ImageSourceKind; +use rufust_helper_protocol::SourceSpec; +use rufust_platform::windows::{ioctl, wide, Handle}; +use windows_sys::Win32::Foundation::{ERROR_SUCCESS, HANDLE}; +use windows_sys::Win32::Storage::FileSystem::{ + GetFinalPathNameByHandleW, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_OPEN_REPARSE_POINT, + FILE_SHARE_READ, VOLUME_NAME_GUID, +}; +use windows_sys::Win32::Storage::Vhd::{ + AttachVirtualDisk, GetVirtualDiskInformation, GetVirtualDiskPhysicalPath, OpenVirtualDisk, + ATTACH_VIRTUAL_DISK_FLAG_NO_DRIVE_LETTER, ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY, + ATTACH_VIRTUAL_DISK_PARAMETERS, ATTACH_VIRTUAL_DISK_VERSION_1, GET_VIRTUAL_DISK_INFO, + GET_VIRTUAL_DISK_INFO_PROVIDER_SUBTYPE, GET_VIRTUAL_DISK_INFO_SIZE, + OPEN_VIRTUAL_DISK_FLAG_NONE, VIRTUAL_DISK_ACCESS_ATTACH_RO, VIRTUAL_DISK_ACCESS_GET_INFO, + VIRTUAL_DISK_ACCESS_READ, VIRTUAL_STORAGE_TYPE, VIRTUAL_STORAGE_TYPE_DEVICE_VHD, + VIRTUAL_STORAGE_TYPE_DEVICE_VHDX, VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT, +}; +use windows_sys::Win32::System::Ioctl::IOCTL_DISK_GET_LENGTH_INFO; + +use crate::HelperError; + +/// Open the selected image, refusing links, and keep others from writing to +/// it while this job runs. +pub(crate) fn bind(source: &SourceSpec) -> Result { + let file = OpenOptions::new() + .read(true) + .share_mode(FILE_SHARE_READ) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) + .open(&source.path) + .map_err(|error| { + HelperError::Operation(format!( + "could not open {} for reading (is another program writing to it?): {error}", + source.path.display() + )) + })?; + let metadata = file.metadata()?; + if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + return Err(HelperError::Operation( + "the source is a link; select the image file itself".into(), + )); + } + if !metadata.is_file() { + return Err(HelperError::Operation( + "source is not a regular file".into(), + )); + } + if metadata.len() != source.size_bytes { + return Err(HelperError::Operation( + "source image size changed since selection".into(), + )); + } + Ok(file) +} + +/// The volume (`\\?\Volume{GUID}\`) holding an open file, if it is local. +pub(crate) fn volume_of(file: &File) -> Option { + let mut buffer = vec![0u16; 1024]; + // SAFETY: the handle is live and the buffer writable for its length. + let length = unsafe { + GetFinalPathNameByHandleW( + file.as_raw_handle(), + buffer.as_mut_ptr(), + buffer.len() as u32, + VOLUME_NAME_GUID, + ) + } as usize; + if length == 0 || length >= buffer.len() { + return None; + } + let path = String::from_utf16_lossy(&buffer[..length]); + let end = path.find("}\\")?; + Some(path[..end + 2].to_owned()) +} + +/// The full path of an open file, for APIs that take a path. +pub(crate) fn final_path(file: &File) -> Option { + let mut buffer = vec![0u16; 4096]; + // SAFETY: the handle is live and the buffer writable for its length. + let length = unsafe { + GetFinalPathNameByHandleW( + file.as_raw_handle(), + buffer.as_mut_ptr(), + buffer.len() as u32, + 0, + ) + } as usize; + (length != 0 && length < buffer.len()) + .then(|| std::path::PathBuf::from(String::from_utf16_lossy(&buffer[..length]))) +} + +/// Built-in decoder for a compressed image, chosen by extension as the +/// Linux helper chooses its external tool. +pub(crate) fn decoder_kind(path: &Path) -> Result<&'static str, HelperError> { + let extension = path + .extension() + .and_then(|value| value.to_str()) + .unwrap_or_default() + .to_ascii_lowercase(); + match extension.as_str() { + "gz" => Ok("gzip"), + "bz2" => Ok("bzip2"), + "xz" => Ok("xz"), + "lzma" => Ok("lzma"), + "zst" | "zstd" => Ok("zstd"), + "zip" => Ok("zip"), + _ => Err(HelperError::Operation( + "this compressed image format is not supported on Windows".into(), + )), + } +} + +/// A pull-based decoder over the bound source. +pub(crate) fn decoder(source: &File, path: &Path) -> Result, HelperError> { + let mut file = source.try_clone()?; + file.seek(SeekFrom::Start(0))?; + let input = BufReader::with_capacity(1024 * 1024, file); + Ok(match decoder_kind(path)? { + "gzip" => Box::new(flate2::read::MultiGzDecoder::new(input)), + "bzip2" => Box::new(bzip2::read::MultiBzDecoder::new(input)), + "xz" => Box::new(lzma_rust2::XzReader::new(input, true)), + "lzma" => Box::new( + lzma_rust2::LzmaReader::new_mem_limit(input, u32::MAX, None) + .map_err(|error| HelperError::Operation(format!("invalid LZMA image: {error}")))?, + ), + "zstd" => Box::new( + ruzstd::StreamingDecoder::new(input) + .map_err(|error| HelperError::Operation(format!("invalid zstd image: {error}")))?, + ), + _ => zip_entry(source.try_clone()?)?, + }) +} + +fn u16_at(bytes: &[u8], at: usize) -> u16 { + u16::from_le_bytes([bytes[at], bytes[at + 1]]) +} + +fn u32_at(bytes: &[u8], at: usize) -> u32 { + u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]) +} + +fn u64_at(bytes: &[u8], at: usize) -> u64 { + u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap_or([0; 8])) +} + +/// The single file inside a zip archive, decompressed. Archives holding +/// several files are refused rather than concatenated. +pub(crate) fn zip_entry(mut file: File) -> Result, HelperError> { + let length = file.metadata()?.len(); + // The end-of-central-directory record sits in the last 64 KiB + 22 bytes. + let tail_length = length.min(65_557); + let mut tail = vec![0u8; tail_length as usize]; + file.seek(SeekFrom::Start(length - tail_length))?; + file.read_exact(&mut tail)?; + let eocd = (0..tail.len().saturating_sub(21)) + .rev() + .find(|at| tail[*at..*at + 4] == [0x50, 0x4B, 0x05, 0x06]) + .ok_or_else(|| HelperError::Operation("not a zip archive".into()))?; + let mut entries = u64::from(u16_at(&tail, eocd + 10)); + let mut directory = u64::from(u32_at(&tail, eocd + 16)); + // Zip64: the locator just before the record points to the real one. + if (entries == 0xFFFF || directory == 0xFFFF_FFFF) && eocd >= 20 { + let locator = eocd - 20; + if tail[locator..locator + 4] == [0x50, 0x4B, 0x06, 0x07] { + let mut record = [0u8; 56]; + file.seek(SeekFrom::Start(u64_at(&tail, locator + 8)))?; + file.read_exact(&mut record)?; + if record[..4] != [0x50, 0x4B, 0x06, 0x06] { + return Err(HelperError::Operation("damaged zip64 archive".into())); + } + entries = u64_at(&record, 32); + directory = u64_at(&record, 48); + } + } + if entries > 4096 { + return Err(HelperError::Operation( + "zip archive has too many entries".into(), + )); + } + file.seek(SeekFrom::Start(directory))?; + let mut found = None; + for _ in 0..entries { + let mut header = [0u8; 46]; + file.read_exact(&mut header)?; + if header[..4] != [0x50, 0x4B, 0x01, 0x02] { + return Err(HelperError::Operation("damaged zip directory".into())); + } + let method = u16_at(&header, 10); + let mut compressed = u64::from(u32_at(&header, 20)); + let mut uncompressed = u64::from(u32_at(&header, 24)); + let name_length = usize::from(u16_at(&header, 28)); + let extra_length = usize::from(u16_at(&header, 30)); + let comment_length = i64::from(u16_at(&header, 32)); + let mut offset = u64::from(u32_at(&header, 42)); + let mut name = vec![0u8; name_length]; + file.read_exact(&mut name)?; + let mut extra = vec![0u8; extra_length]; + file.read_exact(&mut extra)?; + file.seek(SeekFrom::Current(comment_length))?; + if name.last() == Some(&b'/') { + continue; + } + // Zip64 extended information replaces saturated fields in order. + let mut at = 0; + while at + 4 <= extra.len() { + let id = u16_at(&extra, at); + let size = usize::from(u16_at(&extra, at + 2)); + let body = &extra[(at + 4).min(extra.len())..(at + 4 + size).min(extra.len())]; + if id == 1 { + let mut fields = body.chunks_exact(8).map(|c| u64_at(c, 0)); + if uncompressed == 0xFFFF_FFFF { + uncompressed = fields.next().unwrap_or(uncompressed); + } + if compressed == 0xFFFF_FFFF { + compressed = fields.next().unwrap_or(compressed); + } + if offset == 0xFFFF_FFFF { + offset = fields.next().unwrap_or(offset); + } + } + at += 4 + size; + } + if found.is_some() { + return Err(HelperError::Operation( + "the zip archive holds more than one file; extract the image first".into(), + )); + } + found = Some((method, compressed, uncompressed, offset)); + } + let (method, compressed, _uncompressed, offset) = + found.ok_or_else(|| HelperError::Operation("the zip archive is empty".into()))?; + let mut local = [0u8; 30]; + file.seek(SeekFrom::Start(offset))?; + file.read_exact(&mut local)?; + if local[..4] != [0x50, 0x4B, 0x03, 0x04] { + return Err(HelperError::Operation("damaged zip entry".into())); + } + if u16_at(&local, 6) & 1 != 0 { + return Err(HelperError::Operation( + "encrypted zip archives are not supported".into(), + )); + } + let skip = i64::from(u16_at(&local, 26)) + i64::from(u16_at(&local, 28)); + file.seek(SeekFrom::Current(skip))?; + let data = BufReader::with_capacity(1024 * 1024, file).take(compressed); + match method { + 0 => Ok(Box::new(data)), + 8 => Ok(Box::new(flate2::read::DeflateDecoder::new(data))), + other => Err(HelperError::Operation(format!( + "zip compression method {other} is not supported" + ))), + } +} + +/// A VHD or VHDX attached read-only for as long as this value lives. +pub(crate) struct AttachedVirtualDisk { + _virtual_disk: Handle, + pub disk: File, + pub size: u64, +} + +fn storage_type(kind: ImageSourceKind) -> Result { + let device = match kind { + ImageSourceKind::Vhd => VIRTUAL_STORAGE_TYPE_DEVICE_VHD, + ImageSourceKind::Vhdx => VIRTUAL_STORAGE_TYPE_DEVICE_VHDX, + _ => return Err(HelperError::Operation("not a virtual disk".into())), + }; + Ok(VIRTUAL_STORAGE_TYPE { + DeviceId: device, + VendorId: VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT, + }) +} + +fn virtual_disk_error(action: &str, code: u32) -> HelperError { + HelperError::Operation(format!( + "could not {action} the virtual disk: {}", + io::Error::from_raw_os_error(code as i32) + )) +} + +fn open_virtual_disk( + path: &Path, + kind: ImageSourceKind, + access: i32, +) -> Result { + let storage = storage_type(kind)?; + let name = wide(path); + let mut handle: HANDLE = ptr::null_mut(); + // SAFETY: all pointers are valid for the call; parameters may be null. + let status = unsafe { + OpenVirtualDisk( + &storage, + name.as_ptr(), + access, + OPEN_VIRTUAL_DISK_FLAG_NONE, + ptr::null(), + &mut handle, + ) + }; + if status != ERROR_SUCCESS { + return Err(virtual_disk_error("open", status)); + } + Ok(Handle::from_raw(handle)) +} + +fn info(handle: &Handle, version: i32) -> Result { + // SAFETY: zero is a valid starting value for this plain union. + let mut info: GET_VIRTUAL_DISK_INFO = unsafe { std::mem::zeroed() }; + info.Version = version; + let mut size = size_of::() as u32; + // SAFETY: `info` is writable for `size` bytes. + let status = + unsafe { GetVirtualDiskInformation(handle.raw(), &mut size, &mut info, ptr::null_mut()) }; + if status != ERROR_SUCCESS { + return Err(virtual_disk_error("inspect", status)); + } + Ok(info) +} + +/// Virtual capacity of a standalone, 512-byte-sector VHD/VHDX, the same +/// subset the Linux backend accepts. +pub(crate) fn virtual_size(path: &Path, kind: ImageSourceKind) -> Result { + let handle = open_virtual_disk(path, kind, VIRTUAL_DISK_ACCESS_GET_INFO)?; + checked_size(&handle) +} + +fn checked_size(handle: &Handle) -> Result { + // SAFETY: the union member matches the requested version. + let subtype = unsafe { + info(handle, GET_VIRTUAL_DISK_INFO_PROVIDER_SUBTYPE)? + .Anonymous + .ProviderSubtype + }; + if subtype == 4 { + return Err(HelperError::Operation( + "differencing virtual disks depend on a parent and are not supported".into(), + )); + } + // SAFETY: the union member matches the requested version. + let size = unsafe { info(handle, GET_VIRTUAL_DISK_INFO_SIZE)?.Anonymous.Size }; + if size.SectorSize != 512 { + return Err(HelperError::Operation(format!( + "virtual disks with {}-byte sectors are not supported", + size.SectorSize + ))); + } + if size.VirtualSize == 0 { + return Err(HelperError::Operation("the virtual disk is empty".into())); + } + Ok(size.VirtualSize) +} + +/// Attach the image read-only, without drive letters, and open its disk. +pub(crate) fn attach( + path: &Path, + kind: ImageSourceKind, +) -> Result { + let handle = open_virtual_disk( + path, + kind, + VIRTUAL_DISK_ACCESS_ATTACH_RO | VIRTUAL_DISK_ACCESS_READ | VIRTUAL_DISK_ACCESS_GET_INFO, + )?; + let size = checked_size(&handle)?; + // SAFETY: zero is a valid starting value for this parameter block. + let mut parameters: ATTACH_VIRTUAL_DISK_PARAMETERS = unsafe { std::mem::zeroed() }; + parameters.Version = ATTACH_VIRTUAL_DISK_VERSION_1; + // SAFETY: the handle is live and the parameters valid for the call. + let status = unsafe { + AttachVirtualDisk( + handle.raw(), + ptr::null_mut(), + ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY | ATTACH_VIRTUAL_DISK_FLAG_NO_DRIVE_LETTER, + 0, + ¶meters, + ptr::null(), + ) + }; + if status != ERROR_SUCCESS { + return Err(virtual_disk_error("attach", status)); + } + let mut path_buffer = vec![0u16; 512]; + let mut bytes = (path_buffer.len() * 2) as u32; + // SAFETY: the buffer is writable for `bytes` bytes. + let status = + unsafe { GetVirtualDiskPhysicalPath(handle.raw(), &mut bytes, path_buffer.as_mut_ptr()) }; + if status != ERROR_SUCCESS { + return Err(virtual_disk_error("locate", status)); + } + let end = path_buffer + .iter() + .position(|c| *c == 0) + .unwrap_or(path_buffer.len()); + let physical = String::from_utf16_lossy(&path_buffer[..end]); + let disk = OpenOptions::new() + .read(true) + .share_mode(FILE_SHARE_READ | windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE) + .open(&physical) + .map_err(|error| HelperError::Operation(format!("could not read {physical}: {error}")))?; + let mut length = [0u8; 8]; + ioctl(&disk, IOCTL_DISK_GET_LENGTH_INFO, &[], &mut length) + .map_err(|error| HelperError::Operation(format!("could not size {physical}: {error}")))?; + if u64::from_le_bytes(length) != size { + return Err(HelperError::Operation( + "the attached virtual disk size differs from its metadata".into(), + )); + } + Ok(AttachedVirtualDisk { + _virtual_disk: handle, + disk, + size, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + + struct Temp(std::path::PathBuf); + + impl Drop for Temp { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + + fn temp(name: &str, bytes: &[u8]) -> Temp { + let path = + std::env::temp_dir().join(format!("rufust-source-{}-{name}", std::process::id())); + std::fs::write(&path, bytes).expect("fixture"); + Temp(path) + } + + fn read_all(mut reader: Box) -> Vec { + let mut output = Vec::new(); + reader.read_to_end(&mut output).expect("decode"); + output + } + + fn stored_zip(name: &str, body: &[u8], extra_file: bool) -> Vec { + let mut zip = Vec::new(); + let mut central = Vec::new(); + let mut files = vec![(name, body)]; + if extra_file { + files.push(("second.img", body)); + } + for (name, body) in &files { + let offset = zip.len() as u32; + zip.extend_from_slice(&[0x50, 0x4B, 0x03, 0x04, 20, 0, 0, 0, 0, 0]); + zip.extend_from_slice(&[0; 8]); + zip.extend_from_slice(&(body.len() as u32).to_le_bytes()); + zip.extend_from_slice(&(body.len() as u32).to_le_bytes()); + zip.extend_from_slice(&(name.len() as u16).to_le_bytes()); + zip.extend_from_slice(&[0, 0]); + zip.extend_from_slice(name.as_bytes()); + zip.extend_from_slice(body); + central.extend_from_slice(&[0x50, 0x4B, 0x01, 0x02, 20, 0, 20, 0, 0, 0, 0, 0]); + central.extend_from_slice(&[0; 8]); + central.extend_from_slice(&(body.len() as u32).to_le_bytes()); + central.extend_from_slice(&(body.len() as u32).to_le_bytes()); + central.extend_from_slice(&(name.len() as u16).to_le_bytes()); + central.extend_from_slice(&[0; 12]); + central.extend_from_slice(&offset.to_le_bytes()); + central.extend_from_slice(name.as_bytes()); + } + let directory = zip.len() as u32; + zip.extend_from_slice(¢ral); + zip.extend_from_slice(&[0x50, 0x4B, 0x05, 0x06, 0, 0, 0, 0]); + zip.extend_from_slice(&(files.len() as u16).to_le_bytes()); + zip.extend_from_slice(&(files.len() as u16).to_le_bytes()); + zip.extend_from_slice(&(central.len() as u32).to_le_bytes()); + zip.extend_from_slice(&directory.to_le_bytes()); + zip.extend_from_slice(&[0, 0]); + zip + } + + #[test] + fn decodes_gzip_and_zip_images() { + let body = b"rufust image bytes".repeat(1000); + let mut gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); + gzip.write_all(&body).expect("gzip fixture"); + let gz = temp("image.img.gz", &gzip.finish().expect("gzip fixture")); + let file = File::open(&gz.0).expect("open"); + assert_eq!(read_all(decoder(&file, &gz.0).expect("gzip decoder")), body); + + let zip = temp("image.zip", &stored_zip("disk/image.img", &body, false)); + let file = File::open(&zip.0).expect("open"); + assert_eq!(read_all(decoder(&file, &zip.0).expect("zip decoder")), body); + + let two = temp("two.zip", &stored_zip("one.img", &body, true)); + let file = File::open(&two.0).expect("open"); + assert!(decoder(&file, &two.0).is_err()); + } + + #[test] + fn unknown_compression_is_refused() { + assert!(decoder_kind(Path::new("image.img.Z")).is_err()); + assert_eq!(decoder_kind(Path::new("IMAGE.XZ")).ok(), Some("xz")); + assert_eq!(decoder_kind(Path::new("a.zstd")).ok(), Some("zstd")); + } + + #[test] + fn binding_checks_the_selected_size() { + let image = temp("bound.img", &[0u8; 4096]); + let mut spec = SourceSpec { + path: image.0.clone(), + kind: ImageSourceKind::Raw, + size_bytes: 4096, + decompressed_size_bytes: None, + expected_sha256: None, + }; + let bound = bind(&spec).expect("bind"); + assert!(volume_of(&bound).is_some_and(|volume| volume.starts_with(r"\\?\Volume{"))); + drop(bound); + spec.size_bytes = 512; + assert!(bind(&spec).is_err()); + } +} diff --git a/crates/rufust-helper/src/windows/vhd_tests.rs b/crates/rufust-helper/src/windows/vhd_tests.rs new file mode 100644 index 0000000..c52ded1 --- /dev/null +++ b/crates/rufust-helper/src/windows/vhd_tests.rs @@ -0,0 +1,412 @@ +//! End-to-end checks of the Windows engine on a disposable virtual disk. +//! +//! Run elevated, with a VHD(X) attached and its disk number in +//! `RUFUST_TEST_DISK` (and optionally a second one over 32 GB in +//! `RUFUST_TEST_LARGE_DISK` for the large FAT32 path): +//! +//! ```text +//! cargo test -p rufust-helper windows::vhd_tests -- --ignored --test-threads=1 +//! ``` +//! +//! Each test refuses any disk that is not file-backed virtual storage, so a +//! wrong number cannot reach real media. `scripts/windows/vhd-tests.ps1` +//! creates, attaches, and removes the disks. + +use std::fs::File; +use std::io::{Read, Write}; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; + +use rufust_core::plan::{ + BootMode, FileSystem, ImageSourceKind, PartitionScheme, VerificationLevel, WriteMode, +}; +use rufust_core::progress::{CancellationToken, JobId}; +use rufust_helper_protocol::{ + FormatSpec, HelperEvent, HelperOperation, HelperRequest, HelperResult, SourceSpec, + TargetIdentity, PROTOCOL_VERSION, +}; +use rufust_image::isofs::fixture::{self, Node}; +use rufust_platform::windows::{self as platform, wide}; +use windows_sys::Win32::Storage::FileSystem::GetVolumeInformationW; + +use super::*; + +fn target(variable: &str) -> Option { + let number: u32 = std::env::var(variable).ok()?.parse().ok()?; + let identity = discover_devices(true) + .expect("discovery") + .into_iter() + .find(|device| device.minor == number) + .expect("the disk is attached"); + assert_eq!( + identity.transport, "loop", + "refusing disk {number}: it is not a file-backed virtual disk" + ); + Some(identity) +} + +fn request(identity: &DeviceIdentity, operation: HelperOperation) -> HelperRequest { + let block = platform::to_block_device(identity, &platform::volumes()); + HelperRequest { + protocol_version: PROTOCOL_VERSION, + job_id: JobId::new(1), + target: TargetIdentity { + node: identity.node.clone(), + fingerprint: block.fingerprint, + display_name: identity.display_name(), + model: identity.model.clone(), + serial: identity.serial.clone(), + }, + operation, + action_name: "test".into(), + } +} + +fn run(identity: &DeviceIdentity, operation: HelperOperation) -> Vec { + let events = Arc::new(Mutex::new(Vec::new())); + let sink = Arc::clone(&events); + let result = execute( + request(identity, operation), + ExecutionOptions::default(), + Box::new(move |event| sink.lock().expect("events").push(event)), + ); + let events = events.lock().expect("events").clone(); + if let Err(error) = result { + panic!("operation failed: {error}\nevents: {events:#?}"); + } + assert!(events.iter().any(|event| matches!( + event, + HelperEvent::Finished { + result: HelperResult::Success, + .. + } + ))); + events +} + +fn format(scheme: PartitionScheme, filesystem: FileSystem, label: &str) -> FormatSpec { + FormatSpec { + scheme, + boot_mode: BootMode::NonBootable, + filesystem, + label: label.into(), + cluster_size: None, + persistence_bytes: 0, + quick_format: true, + } +} + +/// File system name and label of the volume at `offset` on `disk`. +fn describe(disk: u32, offset: u64) -> (String, String, PathBuf) { + let volume = disk::wait_for_volume(disk, offset, &CancellationToken::new()).expect("volume"); + let name = wide(&volume.name); + let mut label = [0u16; 64]; + let mut filesystem = [0u16; 64]; + // SAFETY: both buffers are writable for their stated lengths. + let ok = unsafe { + GetVolumeInformationW( + name.as_ptr(), + label.as_mut_ptr(), + label.len() as u32, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + filesystem.as_mut_ptr(), + filesystem.len() as u32, + ) + }; + assert_ne!(ok, 0, "volume information: {}", io::Error::last_os_error()); + let text = |buffer: &[u16]| { + let end = buffer.iter().position(|c| *c == 0).unwrap_or(buffer.len()); + String::from_utf16_lossy(&buffer[..end]) + }; + (text(&filesystem), text(&label), PathBuf::from(&volume.name)) +} + +fn read_disk(identity: &DeviceIdentity, offset: u64, length: usize) -> Vec { + let disk = Disk::open( + identity.minor, + identity.size_bytes, + identity.logical_sector_size, + ) + .expect("open disk"); + let mut buffer = AlignedBuffer::new(length); + disk.read_at(offset, buffer.as_mut_slice()).expect("read"); + buffer.as_slice().to_vec() +} + +fn scratch(name: &str) -> PathBuf { + let directory = std::env::temp_dir().join(format!("rufust-vhd-{}", std::process::id())); + std::fs::create_dir_all(&directory).expect("scratch directory"); + directory.join(name) +} + +#[test] +#[ignore = "needs an elevated shell and an attached VHD in RUFUST_TEST_DISK"] +fn formats_with_each_windows_provider() { + let Some(identity) = target("RUFUST_TEST_DISK") else { + return; + }; + for (scheme, filesystem, label, expected) in [ + ( + PartitionScheme::Gpt, + FileSystem::Ntfs, + "Rufust NTFS", + "NTFS", + ), + ( + PartitionScheme::Mbr, + FileSystem::Fat32, + "rufust fat", + "FAT32", + ), + ( + PartitionScheme::Mbr, + FileSystem::ExFat, + "Rufust exFAT", + "exFAT", + ), + (PartitionScheme::Gpt, FileSystem::Udf, "RufustUDF", "UDF"), + ] { + run( + &identity, + HelperOperation::FormatMedia { + format: format(scheme, filesystem, &filesystem.volume_label(label)), + bad_blocks: false, + }, + ); + let (name, volume_label, root) = describe(identity.minor, MIB); + assert_eq!(name, expected, "{scheme:?} {filesystem:?}"); + assert_eq!(volume_label, filesystem.volume_label(label)); + std::fs::write(root.join("probe.txt"), b"rufust").expect("write to new volume"); + assert_eq!( + std::fs::read(root.join("probe.txt")).expect("read"), + b"rufust" + ); + } +} + +#[test] +#[ignore = "needs an elevated shell and an attached VHD in RUFUST_TEST_DISK"] +fn writes_and_verifies_raw_and_compressed_images() { + let Some(identity) = target("RUFUST_TEST_DISK") else { + return; + }; + // A sector-unaligned size exercises the padded final write. + let image = (0..3 * MIB + 100) + .map(|i| (i % 251) as u8) + .collect::>(); + let raw = scratch("image.img"); + std::fs::write(&raw, &image).expect("raw fixture"); + let gz = scratch("image.img.gz"); + let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); + encoder.write_all(&image).expect("gzip"); + std::fs::write(&gz, encoder.finish().expect("gzip")).expect("gz fixture"); + + for (path, kind, expanded) in [ + (&raw, ImageSourceKind::Raw, None), + ( + &gz, + ImageSourceKind::CompressedRaw, + Some(image.len() as u64), + ), + ] { + let size = std::fs::metadata(path).expect("size").len(); + run( + &identity, + HelperOperation::WriteMedia { + write_mode: WriteMode::DdImage, + source: SourceSpec { + path: path.clone(), + kind, + size_bytes: size, + decompressed_size_bytes: expanded, + expected_sha256: Some(hex_lower(&Sha256::digest(&image))), + }, + format: format(PartitionScheme::Mbr, FileSystem::Fat32, ""), + verification: VerificationLevel::FullReadback, + bad_blocks: false, + install_bootloader: None, + windows_customization: None, + }, + ); + let written = read_disk(&identity, 0, (4 * MIB) as usize); + assert_eq!(&written[..image.len()], &image[..], "{kind:?}"); + assert!(written[image.len()..image.len().div_ceil(512) * 512] + .iter() + .all(|byte| *byte == 0)); + } +} + +#[test] +#[ignore = "needs an elevated shell and an attached VHD in RUFUST_TEST_DISK"] +fn builds_windows_installer_media() { + let Some(identity) = target("RUFUST_TEST_DISK") else { + return; + }; + let iso = scratch("windows.iso"); + std::fs::write( + &iso, + fixture::udf(vec![ + Node::File("bootmgr", 50_000), + Node::Dir( + "sources", + vec![ + Node::File("boot.wim", 5_000_000), + Node::File("install.wim", 20_000_000), + ], + ), + Node::Dir( + "efi", + vec![Node::Dir( + "boot", + vec![Node::File("bootx64.efi", 1_500_000)], + )], + ), + ]), + ) + .expect("ISO fixture"); + let size = std::fs::metadata(&iso).expect("size").len(); + for (scheme, boot_mode, filesystem) in [ + (PartitionScheme::Mbr, BootMode::Dual, FileSystem::Ntfs), + (PartitionScheme::Gpt, BootMode::Uefi, FileSystem::Ntfs), + (PartitionScheme::Mbr, BootMode::Dual, FileSystem::Fat32), + ] { + let mut spec = format(scheme, filesystem, "CCCOMA_X64FRE"); + spec.boot_mode = boot_mode; + let events = run( + &identity, + HelperOperation::WriteMedia { + write_mode: WriteMode::IsoFileCopy, + source: SourceSpec { + path: iso.clone(), + kind: ImageSourceKind::Iso, + size_bytes: size, + decompressed_size_bytes: None, + expected_sha256: None, + }, + format: spec, + verification: VerificationLevel::FullReadback, + bad_blocks: false, + install_bootloader: None, + windows_customization: None, + }, + ); + assert!(events.iter().any(|event| matches!( + event, + HelperEvent::Progress { + stage: ProgressStage::Verifying, + .. + } + ))); + let (name, _, root) = describe(identity.minor, MIB); + assert_eq!(name, filesystem.as_str()); + let mut install = Vec::new(); + File::open(root.join("sources").join("install.wim")) + .expect("install.wim") + .read_to_end(&mut install) + .expect("read install.wim"); + assert_eq!(install.len(), 20_000_000); + // The fixture stores files over 64 KiB as zero extents. + assert!(install.iter().all(|byte| *byte == 0)); + let bootmgr = std::fs::read(root.join("bootmgr")).expect("bootmgr"); + assert_eq!(bootmgr.len(), 50_000); + assert!(bootmgr + .iter() + .enumerate() + .all(|(i, byte)| *byte == fixture::pattern(i as u64))); + + let mbr = read_disk(&identity, 0, 512); + let uefi_ntfs = filesystem == FileSystem::Ntfs; + if scheme == PartitionScheme::Mbr { + // Windows 7 boot code, an active data partition, and 0xEF. + assert_eq!(&mbr[..440], &winmedia_mbr()[..440]); + assert_eq!(mbr[446], 0x80); + assert_eq!(mbr[446 + 16 + 4], if uefi_ntfs { 0xef } else { 0 }); + let boot = read_disk(&identity, MIB, 512); + assert_eq!(&boot[510..], &[0x55, 0xaa]); + } else { + assert_eq!(mbr[446 + 4], 0xee, "protective MBR"); + } + if uefi_ntfs { + let span = winmedia::plan_layout( + identity.size_bytes, + u64::from(identity.logical_sector_size), + scheme, + true, + ) + .expect("layout") + .uefi_ntfs + .expect("UEFI:NTFS"); + let (name, label, root) = describe(identity.minor, span.offset); + assert_eq!(name, "FAT"); + assert_eq!(label, winmedia::UEFI_NTFS_LABEL); + assert!(root.join("EFI").join("Boot").join("bootx64.efi").is_file()); + } + } +} + +fn winmedia_mbr() -> Vec { + let mut sector = vec![0u8; 512]; + winmedia::patch_mbr(&mut sector).expect("patch"); + sector +} + +#[test] +#[ignore = "needs an elevated shell and a VHD over 32 GB in RUFUST_TEST_LARGE_DISK"] +fn formats_large_fat32_itself() { + let Some(identity) = target("RUFUST_TEST_LARGE_DISK") else { + return; + }; + assert!(identity.size_bytes > LARGE_FAT32 + GIB); + run( + &identity, + HelperOperation::FormatMedia { + format: format(PartitionScheme::Mbr, FileSystem::Fat32, "big fat"), + bad_blocks: false, + }, + ); + let (name, label, root) = describe(identity.minor, MIB); + assert_eq!(name, "FAT32"); + assert_eq!(label, "BIG FAT"); + std::fs::write(root.join("probe.txt"), b"rufust").expect("write"); + assert_eq!( + std::fs::read(root.join("probe.txt")).expect("read"), + b"rufust" + ); +} + +#[test] +#[ignore = "needs an elevated shell, RUFUST_TEST_DISK, and RUFUST_TEST_VHD_SOURCE"] +fn writes_a_virtual_disk_image() { + let Some(identity) = target("RUFUST_TEST_DISK") else { + return; + }; + let Some(source) = std::env::var_os("RUFUST_TEST_VHD_SOURCE").map(PathBuf::from) else { + return; + }; + let report = rufust_image::analyze(&source).expect("analyze"); + assert!(matches!( + report.kind, + ImageSourceKind::Vhd | ImageSourceKind::Vhdx + )); + let expanded = source::virtual_size(&source, report.kind).expect("virtual size"); + run( + &identity, + HelperOperation::WriteMedia { + write_mode: WriteMode::DdImage, + source: SourceSpec { + path: source.clone(), + kind: report.kind, + size_bytes: report.size_bytes, + decompressed_size_bytes: Some(expanded), + expected_sha256: None, + }, + format: format(PartitionScheme::Mbr, FileSystem::Fat32, ""), + verification: VerificationLevel::FullReadback, + bad_blocks: false, + install_bootloader: None, + windows_customization: None, + }, + ); +} diff --git a/crates/rufust-helper/src/windows_media.rs b/crates/rufust-helper/src/windows_media.rs index 6d5d357..5504258 100644 --- a/crates/rufust-helper/src/windows_media.rs +++ b/crates/rufust-helper/src/windows_media.rs @@ -27,9 +27,11 @@ pub(crate) const UEFI_NTFS_SIZE: u64 = MIB; pub(crate) const UEFI_NTFS_NAME: &str = "UEFI:NTFS"; pub(crate) const UEFI_NTFS_LABEL: &str = "UEFI_NTFS"; pub(crate) const MAIN_PARTITION_NAME: &str = "Main Data Partition"; +#[cfg(target_os = "linux")] pub(crate) const GPT_BASIC_DATA: &str = "ebd0a0a2-b9e5-4433-87c0-68b6b72699c7"; /// GPT_BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER. pub(crate) const GPT_NO_DRIVE_LETTER: u64 = 1 << 63; +#[cfg(target_os = "linux")] pub(crate) const MBR_ACTIVE: u64 = 0x80; macro_rules! payload { @@ -77,6 +79,7 @@ pub(crate) struct Span { } impl Span { + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] pub fn end(self) -> u64 { self.offset + self.size } @@ -231,16 +234,23 @@ fn destination(root: &Path, relative: &str) -> Result { relative.display() ))); } - Ok(root.join(relative)) + // Push each name so the separators suit the platform; Windows volume + // paths (`\?Volume{...}`) are verbatim and take no `/`. + let mut path = root.to_owned(); + path.extend(relative.components()); + Ok(path) } fn create_new(path: &Path) -> io::Result { - use std::os::unix::fs::OpenOptionsExt; - std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) - .open(path) + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC); + } + // On Windows, CREATE_NEW already refuses an existing link. + options.open(path) } fn ensure_parent(path: &Path, root: &Path) -> Result<(), HelperError> { @@ -411,7 +421,7 @@ fn find_copy<'a>( relative: &str, copies: &'a mut [CopiedFile], ) -> Option<&'a mut CopiedFile> { - let wanted = root.join(relative); + let wanted = destination(root, relative).ok()?; copies.iter_mut().find(|copy| { copy.path .to_str() @@ -607,7 +617,6 @@ pub(crate) fn patch_boot_record( mod tests { use super::*; use rufust_image::isofs::fixture::{self, Node}; - use std::os::unix::fs::DirBuilderExt; const GIB: u64 = 1024 * MIB; @@ -623,10 +632,14 @@ mod tests { .expect("clock") .as_nanos() )); - std::fs::DirBuilder::new() - .mode(0o700) - .create(&path) - .expect("temporary directory"); + #[cfg_attr(not(unix), allow(unused_mut))] + let mut builder = std::fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + builder.create(&path).expect("temporary directory"); Self(path) } } diff --git a/crates/rufust-image/src/lib.rs b/crates/rufust-image/src/lib.rs index 779e86b..1209c78 100644 --- a/crates/rufust-image/src/lib.rs +++ b/crates/rufust-image/src/lib.rs @@ -2,7 +2,6 @@ use std::fs::File; use std::io::{self, Read, Seek, SeekFrom}; -use std::os::unix::fs::OpenOptionsExt; use std::path::{Path, PathBuf}; use md5::{Digest as _, Md5}; @@ -74,10 +73,15 @@ impl ImageReport { /// Probe an image file without extracting contents. pub fn analyze(path: &Path) -> Result { - let mut file = std::fs::OpenOptions::new() - .read(true) - .custom_flags(libc::O_NONBLOCK) - .open(path)?; + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + // A FIFO must not block the open waiting for a writer. + options.custom_flags(libc::O_NONBLOCK); + } + let mut file = options.open(path)?; analyze_file(path, &mut file) } @@ -631,6 +635,7 @@ mod tests { } #[test] + #[cfg(unix)] fn named_pipe_is_rejected_without_waiting_for_a_writer() { use std::os::unix::ffi::OsStrExt; let path = temp_path("fifo"); diff --git a/crates/rufust-platform/Cargo.toml b/crates/rufust-platform/Cargo.toml index 3e10ca3..13dd238 100644 --- a/crates/rufust-platform/Cargo.toml +++ b/crates/rufust-platform/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rufust-platform" -description = "Linux sysfs/mount discovery and capability probing for Rufust" +description = "Linux and Windows disk discovery and capability probing for Rufust" version.workspace = true edition.workspace = true rust-version.workspace = true @@ -13,3 +13,15 @@ workspace = true [dependencies] rufust-core = { path = "../rufust-core" } + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.59", features = [ + "Win32_Devices_DeviceAndDriverInstallation", + "Win32_Foundation", + "Win32_Security", + "Win32_Storage_FileSystem", + "Win32_System_IO", + "Win32_System_Ioctl", + "Win32_System_Registry", + "Win32_System_SystemInformation", +] } diff --git a/crates/rufust-platform/src/lib.rs b/crates/rufust-platform/src/lib.rs index 1d39f7a..761568e 100644 --- a/crates/rufust-platform/src/lib.rs +++ b/crates/rufust-platform/src/lib.rs @@ -1,17 +1,27 @@ -//! Linux platform integration kept separate from the portable planning core. +//! Linux and Windows platform integration kept separate from the portable +//! planning core. //! -//! Discovery reads sysfs rather than parsing human-facing `lsblk` output. +//! On Linux, discovery reads sysfs rather than parsing human-facing `lsblk` +//! output. On Windows, it queries each disk interface with storage IOCTLs. //! Destructive jobs must revalidate a returned [`DeviceIdentity`] inside the //! privileged helper immediately before opening the block device. use std::fmt; use std::path::{Path, PathBuf}; -use rufust_core::capability::{Capability, CapabilityReport, CapabilityState, MissingRequirement}; +use rufust_core::capability::CapabilityReport; +#[cfg(not(windows))] +use rufust_core::capability::{Capability, CapabilityState, MissingRequirement}; use rufust_core::device::{ BlockDevice, DeviceClass, DeviceFingerprint, DeviceNumber, DeviceRisk, Transport, }; +#[cfg(windows)] +pub mod windows; + +/// A disk as the platform reports it. On Windows, `node` is +/// `\\.\PhysicalDriveN`, `sysfs_path` is the disk's device interface path, +/// `major` is 0, and `minor` is the disk number. #[derive(Clone, Debug, PartialEq, Eq)] pub struct DeviceIdentity { pub node: PathBuf, @@ -198,6 +208,18 @@ pub fn mount_belongs_to_identity(mount: &MountRecord, device: &DeviceIdentity) - /// Conservative source-on-target check based on the longest containing mount. pub fn path_is_on_block_device(path: &Path, device: &BlockDevice) -> bool { + #[cfg(windows)] + { + windows::path_is_on_block_device(path, device) + } + #[cfg(not(windows))] + { + path_is_on_mounted_block_device(path, device) + } +} + +#[cfg(not(windows))] +fn path_is_on_mounted_block_device(path: &Path, device: &BlockDevice) -> bool { let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_owned()); let mut mounts = mount_records().unwrap_or_default(); mounts.sort_by_key(|mount| std::cmp::Reverse(mount.mount_point.as_os_str().len())); @@ -234,7 +256,14 @@ fn source_is_device_or_partition(source: &str, disk: &Path) -> bool { } pub fn discover_devices(show_fixed: bool) -> Result, PlatformError> { - discover_devices_from(Path::new("/sys/class/block"), show_fixed) + #[cfg(windows)] + { + windows::discover_devices(show_fixed) + } + #[cfg(not(windows))] + { + discover_devices_from(Path::new("/sys/class/block"), show_fixed) + } } pub fn discover_devices_from( @@ -256,6 +285,18 @@ pub fn discover_devices_from( /// Discover devices and map them into core [`BlockDevice`] values with risk tags. pub fn list_block_devices(show_fixed: bool) -> Result, PlatformError> { + #[cfg(windows)] + { + windows::list_block_devices(show_fixed) + } + #[cfg(not(windows))] + { + list_mounted_block_devices(show_fixed) + } +} + +#[cfg(not(windows))] +fn list_mounted_block_devices(show_fixed: bool) -> Result, PlatformError> { let mounts = mount_records().unwrap_or_default(); let identities = discover_devices(show_fixed)?; Ok(identities @@ -322,6 +363,18 @@ fn unescape_mount_field(value: &str) -> String { /// Probe installed tools and return a capability report. pub fn probe_capabilities() -> CapabilityReport { + #[cfg(windows)] + { + windows::probe_capabilities() + } + #[cfg(not(windows))] + { + probe_linux_capabilities() + } +} + +#[cfg(not(windows))] +fn probe_linux_capabilities() -> CapabilityReport { let mut report = CapabilityReport::new(); let set_tool = |report: &mut CapabilityReport, @@ -814,9 +867,15 @@ mod tests { #[test] fn capability_probe_marks_refs_unavailable() { + use rufust_core::capability::Capability; let report = probe_capabilities(); assert!(!report.supports(Capability::FormatRefs)); assert!(!report.supports(Capability::ImageCaptureFfu)); + if cfg!(windows) { + assert!(report.supports(Capability::RawImageWrite)); + assert!(!report.supports(Capability::FormatExt4)); + return; + } let tools = [ Path::new("/usr/bin/qemu-nbd").exists(), Path::new("/usr/bin/nbdinfo").exists(), diff --git a/crates/rufust-platform/src/windows.rs b/crates/rufust-platform/src/windows.rs new file mode 100644 index 0000000..b06200f --- /dev/null +++ b/crates/rufust-platform/src/windows.rs @@ -0,0 +1,867 @@ +//! Windows disk discovery through the storage IOCTLs. +//! +//! Disks are enumerated through their device interfaces, so a disk's +//! interface path (which embeds the PnP instance ID) stands in for the Linux +//! sysfs path as its stable identity. `\\.\PhysicalDriveN` is the node and +//! only a display name. Every query here opens devices with no access rights, +//! which an unelevated desktop process may do; destructive work stays in the +//! elevated helper. + +use std::ffi::{OsStr, OsString}; +use std::io; +use std::os::windows::ffi::{OsStrExt, OsStringExt}; +use std::os::windows::io::{AsRawHandle, RawHandle}; +use std::path::{Path, PathBuf}; +use std::ptr; + +use rufust_core::capability::{Capability, CapabilityReport, CapabilityState, MissingRequirement}; +use rufust_core::device::{BlockDevice, DeviceRisk}; +use windows_sys::Win32::Devices::DeviceAndDriverInstallation::{ + SetupDiDestroyDeviceInfoList, SetupDiEnumDeviceInterfaces, SetupDiGetClassDevsW, + SetupDiGetDeviceInterfaceDetailW, DIGCF_DEVICEINTERFACE, DIGCF_PRESENT, + SP_DEVICE_INTERFACE_DATA, SP_DEVICE_INTERFACE_DETAIL_DATA_W, +}; +use windows_sys::Win32::Foundation::{ + CloseHandle, GetLastError, ERROR_MORE_DATA, ERROR_WRITE_PROTECT, HANDLE, INVALID_HANDLE_VALUE, + MAX_PATH, +}; +use windows_sys::Win32::Storage::FileSystem::{ + CreateFileW, FindFirstVolumeW, FindNextVolumeW, FindVolumeClose, + GetVolumeNameForVolumeMountPointW, GetVolumePathNameW, GetVolumePathNamesForVolumeNameW, + QueryDosDeviceW, FILE_SHARE_READ, FILE_SHARE_WRITE, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, + OPEN_EXISTING, +}; +use windows_sys::Win32::System::Ioctl::{ + GUID_DEVINTERFACE_DISK, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IOCTL_DISK_IS_WRITABLE, + IOCTL_STORAGE_GET_DEVICE_NUMBER, IOCTL_STORAGE_QUERY_PROPERTY, +}; +use windows_sys::Win32::System::Registry::{RegGetValueW, HKEY_LOCAL_MACHINE, RRF_RT_REG_SZ}; +use windows_sys::Win32::System::SystemInformation::GetWindowsDirectoryW; +use windows_sys::Win32::System::IO::DeviceIoControl; + +use super::{DeviceIdentity, PlatformError}; + +/// An owned Win32 handle, closed on drop. +#[derive(Debug)] +pub struct Handle(HANDLE); + +impl Handle { + /// Take ownership of a live handle that nothing else will close. + pub fn from_raw(handle: HANDLE) -> Self { + Self(handle) + } + + pub fn raw(&self) -> HANDLE { + self.0 + } +} + +impl AsRawHandle for Handle { + fn as_raw_handle(&self) -> RawHandle { + self.0 + } +} + +impl Drop for Handle { + fn drop(&mut self) { + // SAFETY: the handle is owned and closed exactly once. + unsafe { CloseHandle(self.0) }; + } +} + +// SAFETY: kernel handles may be used from any thread. +unsafe impl Send for Handle {} +unsafe impl Sync for Handle {} + +/// NUL-terminated UTF-16 for a Win32 call. +pub fn wide(value: impl AsRef) -> Vec { + value.as_ref().encode_wide().chain(Some(0)).collect() +} + +fn from_wide(buffer: &[u16]) -> String { + let end = buffer.iter().position(|c| *c == 0).unwrap_or(buffer.len()); + OsString::from_wide(&buffer[..end]) + .to_string_lossy() + .into_owned() +} + +/// Open a device or volume path with exactly the requested access. +pub fn open(path: impl AsRef, access: u32, flags: u32) -> io::Result { + let name = wide(path); + // SAFETY: `name` is NUL-terminated and outlives the call. + let handle = unsafe { + CreateFileW( + name.as_ptr(), + access, + FILE_SHARE_READ | FILE_SHARE_WRITE, + ptr::null(), + OPEN_EXISTING, + flags, + ptr::null_mut(), + ) + }; + if handle == INVALID_HANDLE_VALUE { + return Err(io::Error::last_os_error()); + } + Ok(Handle(handle)) +} + +/// One buffered `DeviceIoControl`; returns the number of output bytes. +pub fn ioctl( + device: &impl AsRawHandle, + code: u32, + input: &[u8], + output: &mut [u8], +) -> io::Result { + let mut returned = 0u32; + // SAFETY: the handle is live for the borrow, and both buffers are valid + // for their stated lengths. + let ok = unsafe { + DeviceIoControl( + device.as_raw_handle(), + code, + if input.is_empty() { + ptr::null() + } else { + input.as_ptr().cast() + }, + input.len() as u32, + if output.is_empty() { + ptr::null_mut() + } else { + output.as_mut_ptr().cast() + }, + output.len() as u32, + &mut returned, + ptr::null_mut(), + ) + }; + if ok == 0 { + return Err(io::Error::last_os_error()); + } + Ok(returned as usize) +} + +fn u32_at(bytes: &[u8], offset: usize) -> u32 { + bytes + .get(offset..offset + 4) + .and_then(|b| b.try_into().ok()) + .map_or(0, u32::from_le_bytes) +} + +fn u64_at(bytes: &[u8], offset: usize) -> u64 { + bytes + .get(offset..offset + 8) + .and_then(|b| b.try_into().ok()) + .map_or(0, u64::from_le_bytes) +} + +/// `\\.\PhysicalDriveN` for disk number N. +pub fn physical_drive_path(number: u32) -> PathBuf { + PathBuf::from(format!(r"\\.\PhysicalDrive{number}")) +} + +/// The disk number of a `\\.\PhysicalDriveN` node. +pub fn disk_number(node: &Path) -> Option { + let text = node.to_str()?; + let digits = text + .strip_prefix(r"\\.\PhysicalDrive") + .or_else(|| text.strip_prefix(r"\\.\PHYSICALDRIVE"))?; + if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) { + return None; + } + digits.parse().ok() +} + +/// A region of a disk that a volume occupies. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Extent { + pub disk: u32, + pub offset: u64, + pub length: u64, +} + +/// A mounted (or mountable) volume and where it lives. +#[derive(Clone, Debug)] +pub struct Volume { + /// `\\?\Volume{GUID}\`, with the trailing backslash. + pub name: String, + /// The NT device, such as `\Device\HarddiskVolume3`. + pub device: String, + /// Drive letters and folder mount points. + pub mount_points: Vec, + pub extents: Vec, +} + +impl Volume { + /// `\\.\Volume{GUID}` (no trailing backslash) opens the volume itself. + pub fn device_path(&self) -> String { + format!( + r"\\.\{}", + self.name.trim_start_matches(r"\\?\").trim_end_matches('\\') + ) + } + + pub fn on_disk(&self, disk: u32) -> bool { + self.extents.iter().any(|extent| extent.disk == disk) + } +} + +/// Every volume the volume manager currently knows. +pub fn volumes() -> Vec { + let mut volumes = Vec::new(); + let mut name = [0u16; MAX_PATH as usize + 1]; + // SAFETY: the buffer is writable for its stated length. + let find = unsafe { FindFirstVolumeW(name.as_mut_ptr(), name.len() as u32) }; + if find == INVALID_HANDLE_VALUE { + return volumes; + } + loop { + let volume = from_wide(&name); + if let Some(entry) = describe_volume(&volume) { + volumes.push(entry); + } + // SAFETY: `find` is a live search handle and the buffer is writable. + if unsafe { FindNextVolumeW(find, name.as_mut_ptr(), name.len() as u32) } == 0 { + break; + } + } + // SAFETY: closes the search handle opened above. + unsafe { FindVolumeClose(find) }; + volumes +} + +fn describe_volume(name: &str) -> Option { + let guid = name.strip_prefix(r"\\?\")?.trim_end_matches('\\'); + let mut volume = Volume { + name: name.to_owned(), + device: String::new(), + mount_points: mount_points(name), + extents: Vec::new(), + }; + let mut device = [0u16; 512]; + let query = wide(guid); + // SAFETY: `query` is NUL-terminated and `device` writable. + if unsafe { QueryDosDeviceW(query.as_ptr(), device.as_mut_ptr(), device.len() as u32) } != 0 { + volume.device = from_wide(&device); + } + // Floppies and empty card readers have no extents; they are not disks. + let handle = open(volume.device_path(), 0, 0).ok()?; + let mut buffer = vec![0u8; 8 + 24 * 32]; + let length = ioctl( + &handle, + IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, + &[], + &mut buffer, + ) + .ok()?; + let count = u32_at(&buffer, 0) as usize; + for index in 0..count { + let at = 8 + index * 24; + if at + 24 > length { + break; + } + volume.extents.push(Extent { + disk: u32_at(&buffer, at), + offset: u64_at(&buffer, at + 8), + length: u64_at(&buffer, at + 16), + }); + } + Some(volume) +} + +fn mount_points(volume: &str) -> Vec { + let name = wide(volume); + let mut buffer = vec![0u16; 1024]; + loop { + let mut needed = 0u32; + // SAFETY: the buffer is writable for its stated length. + let ok = unsafe { + GetVolumePathNamesForVolumeNameW( + name.as_ptr(), + buffer.as_mut_ptr(), + buffer.len() as u32, + &mut needed, + ) + }; + if ok != 0 { + break; + } + // SAFETY: reads this thread's last error. + if unsafe { GetLastError() } == ERROR_MORE_DATA && (needed as usize) > buffer.len() { + buffer.resize(needed as usize, 0); + continue; + } + return Vec::new(); + } + buffer + .split(|c| *c == 0) + .take_while(|part| !part.is_empty()) + .map(|part| PathBuf::from(OsString::from_wide(part))) + .collect() +} + +/// The volume GUID path (`\\?\Volume{GUID}\`) that holds `path`. +pub fn volume_of_path(path: &Path) -> Option { + let path = wide(path); + let mut root = [0u16; MAX_PATH as usize + 1]; + // SAFETY: both buffers are valid for their stated lengths. + if unsafe { GetVolumePathNameW(path.as_ptr(), root.as_mut_ptr(), root.len() as u32) } == 0 { + return None; + } + let mut name = [0u16; MAX_PATH as usize + 1]; + // SAFETY: `root` is NUL-terminated and `name` is writable. + if unsafe { + GetVolumeNameForVolumeMountPointW(root.as_ptr(), name.as_mut_ptr(), name.len() as u32) + } == 0 + { + return None; + } + Some(from_wide(&name)) +} + +/// The disks that store `path`, or nothing for network and unknown paths. +pub fn disks_holding_path(path: &Path) -> Vec { + let Some(volume) = volume_of_path(path) else { + return Vec::new(); + }; + describe_volume(&volume) + .map(|volume| volume.extents.iter().map(|extent| extent.disk).collect()) + .unwrap_or_default() +} + +fn disk_interfaces() -> io::Result> { + // SAFETY: the GUID is a static and the returned set is destroyed below. + let set = unsafe { + SetupDiGetClassDevsW( + &GUID_DEVINTERFACE_DISK, + ptr::null(), + ptr::null_mut(), + DIGCF_PRESENT | DIGCF_DEVICEINTERFACE, + ) + }; + if set == INVALID_HANDLE_VALUE as isize { + return Err(io::Error::last_os_error()); + } + let mut paths = Vec::new(); + for index in 0.. { + let mut data = SP_DEVICE_INTERFACE_DATA { + cbSize: size_of::() as u32, + InterfaceClassGuid: GUID_DEVINTERFACE_DISK, + Flags: 0, + Reserved: 0, + }; + // SAFETY: `set` is live and `data` is initialized with its size. + if unsafe { + SetupDiEnumDeviceInterfaces(set, ptr::null(), &GUID_DEVINTERFACE_DISK, index, &mut data) + } == 0 + { + // ERROR_NO_MORE_ITEMS ends the list; any other failure ends it too. + break; + } + // The detail record is a u32 size followed by the path. + let mut buffer = vec![0u32; 1024]; + let detail = buffer + .as_mut_ptr() + .cast::(); + // SAFETY: the buffer is u32-aligned and large enough for the header. + unsafe { (*detail).cbSize = size_of::() as u32 }; + // SAFETY: the buffer is valid for its byte length. + let ok = unsafe { + SetupDiGetDeviceInterfaceDetailW( + set, + &data, + detail, + (buffer.len() * 4) as u32, + ptr::null_mut(), + ptr::null_mut(), + ) + }; + if ok == 0 { + continue; + } + // SAFETY: the path starts after the u32 size field. + let path = unsafe { + std::slice::from_raw_parts( + buffer.as_ptr().cast::().add(4).cast::(), + (buffer.len() * 4 - 4) / 2, + ) + }; + paths.push(from_wide(path)); + } + // SAFETY: destroys the set created above. + unsafe { SetupDiDestroyDeviceInfoList(set) }; + paths.sort(); + Ok(paths) +} + +/// STORAGE_BUS_TYPE values that identify the transport. +fn transport_name(bus: u32) -> &'static str { + match bus { + 7 => "usb", + 17 => "nvme", + 12 | 13 => "mmc", + 3 | 11 => "ata", + 1 | 10 => "scsi", + // BusTypeVirtual and BusTypeFileBackedVirtual: VHDs and RAM disks. + 14 | 15 => "loop", + _ => "unknown", + } +} + +fn descriptor_string(bytes: &[u8], offset: u32) -> String { + let offset = offset as usize; + if offset == 0 || offset >= bytes.len() { + return String::new(); + } + let end = bytes[offset..] + .iter() + .position(|b| *b == 0) + .map_or(bytes.len(), |end| offset + end); + String::from_utf8_lossy(&bytes[offset..end]) + .trim() + .to_owned() +} + +fn identify(interface: &str) -> Option { + let handle = open(interface, 0, 0).ok()?; + let mut number = [0u8; 12]; + ioctl(&handle, IOCTL_STORAGE_GET_DEVICE_NUMBER, &[], &mut number).ok()?; + let disk = u32_at(&number, 4); + + // STORAGE_PROPERTY_QUERY { StorageDeviceProperty, PropertyStandardQuery }. + let query = [0u8; 12]; + let mut descriptor = vec![0u8; 4096]; + let length = ioctl( + &handle, + IOCTL_STORAGE_QUERY_PROPERTY, + &query, + &mut descriptor, + ) + .ok()?; + let descriptor = &descriptor[..length]; + let removable = descriptor.get(10).is_some_and(|value| *value != 0); + let vendor = descriptor_string(descriptor, u32_at(descriptor, 12)); + let model = descriptor_string(descriptor, u32_at(descriptor, 16)); + let serial = descriptor_string(descriptor, u32_at(descriptor, 24)); + let bus = u32_at(descriptor, 28); + + // DISK_GEOMETRY_EX: BytesPerSector at 20, DiskSize at 24. Fails for an + // empty card reader, which is not a usable target. + let mut geometry = [0u8; 256]; + ioctl( + &handle, + IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, + &[], + &mut geometry, + ) + .ok()?; + let logical_sector_size = u32_at(&geometry, 20); + let size_bytes = u64_at(&geometry, 24); + + let read_only = matches!( + ioctl(&handle, IOCTL_DISK_IS_WRITABLE, &[], &mut []), + Err(error) if error.raw_os_error() == Some(ERROR_WRITE_PROTECT as i32) + ); + Some(DeviceIdentity { + node: physical_drive_path(disk), + sysfs_path: PathBuf::from(interface), + kernel_name: format!("PhysicalDrive{disk}"), + major: 0, + minor: disk, + size_bytes, + logical_sector_size, + model, + vendor, + serial, + transport: transport_name(bus).to_owned(), + removable, + read_only, + }) +} + +pub(super) fn discover_devices(show_fixed: bool) -> Result, PlatformError> { + let interfaces = disk_interfaces() + .map_err(|error| PlatformError::Io(format!("could not list disks: {error}")))?; + let mut devices = interfaces + .iter() + .filter_map(|interface| identify(interface)) + .filter(|device| show_fixed || device.removable) + // Like upstream, skip tiny (floppy-like) devices under 8 MiB. + .filter(|device| device.size_bytes >= 8 * 1024 * 1024) + .filter(|device| { + device.logical_sector_size >= 512 && device.logical_sector_size.is_power_of_two() + }) + .collect::>(); + devices.sort_by_key(|device| device.minor); + Ok(devices) +} + +/// The volumes Windows itself runs from. +struct SystemVolumes { + /// The volume holding the Windows directory. + windows: Option, + /// The NT device of the boot (system) partition, such as the ESP. + system_partition: Option, +} + +impl SystemVolumes { + fn read() -> Self { + let mut directory = [0u16; MAX_PATH as usize + 1]; + // SAFETY: the buffer is writable for its stated length. + let length = + unsafe { GetWindowsDirectoryW(directory.as_mut_ptr(), directory.len() as u32) }; + let windows = (length != 0) + .then(|| volume_of_path(Path::new(&from_wide(&directory)))) + .flatten(); + Self { + windows, + system_partition: registry_string(r"SYSTEM\Setup", "SystemPartition"), + } + } +} + +/// A `REG_SZ` value from HKEY_LOCAL_MACHINE. +pub fn registry_string(key: &str, value: &str) -> Option { + let key = wide(key); + let value = wide(value); + let mut buffer = [0u16; 512]; + let mut size = (buffer.len() * 2) as u32; + // SAFETY: all strings are NUL-terminated and the buffer size is in bytes. + let status = unsafe { + RegGetValueW( + HKEY_LOCAL_MACHINE, + key.as_ptr(), + value.as_ptr(), + RRF_RT_REG_SZ, + ptr::null_mut(), + buffer.as_mut_ptr().cast(), + &mut size, + ) + }; + (status == 0).then(|| from_wide(&buffer)) +} + +/// Risks that only the volume table shows. +fn volume_risks(disk: u32, volumes: &[Volume], system: &SystemVolumes) -> Vec { + let on_disk = volumes + .iter() + .filter(|volume| volume.on_disk(disk)) + .collect::>(); + let mut risks = Vec::new(); + if on_disk + .iter() + .any(|volume| system.windows.as_deref() == Some(volume.name.as_str())) + { + risks.push(DeviceRisk::ContainsRoot); + } + if on_disk.iter().any(|volume| { + !volume.device.is_empty() + && system + .system_partition + .as_deref() + .is_some_and(|device| device.eq_ignore_ascii_case(&volume.device)) + }) { + risks.push(DeviceRisk::ContainsBoot); + } + if on_disk.iter().any(|volume| { + volume + .mount_points + .iter() + .any(|mount| mount.join("pagefile.sys").exists() || mount.join("swapfile.sys").exists()) + }) { + risks.push(DeviceRisk::ContainsSwap); + } + if !risks.contains(&DeviceRisk::ContainsRoot) + && on_disk.iter().any(|volume| !volume.mount_points.is_empty()) + { + risks.push(DeviceRisk::MountedChildren); + } + // A volume that spans several disks (a dynamic or Storage Spaces volume). + if on_disk + .iter() + .any(|volume| volume.extents.iter().any(|extent| extent.disk != disk)) + { + risks.push(DeviceRisk::ActiveVolumeMember); + } + risks +} + +/// Map a discovered disk into a [`BlockDevice`] with its Windows risks. +pub fn to_block_device(identity: &DeviceIdentity, volumes: &[Volume]) -> BlockDevice { + let system = SystemVolumes::read(); + block_device_with(identity, volumes, &system) +} + +fn block_device_with( + identity: &DeviceIdentity, + volumes: &[Volume], + system: &SystemVolumes, +) -> BlockDevice { + let mut device = identity.to_block_device(&[]); + for risk in volume_risks(identity.minor, volumes, system) { + if !device.risks.contains(&risk) { + device.risks.push(risk); + } + } + device +} + +pub(super) fn list_block_devices(show_fixed: bool) -> Result, PlatformError> { + let identities = discover_devices(show_fixed)?; + let volumes = volumes(); + let system = SystemVolumes::read(); + Ok(identities + .iter() + .map(|identity| block_device_with(identity, &volumes, &system)) + .collect()) +} + +pub(super) fn path_is_on_block_device(path: &Path, device: &BlockDevice) -> bool { + let Some(disk) = disk_number(&device.node) else { + return false; + }; + disks_holding_path(path).contains(&disk) +} + +/// A cheap fingerprint of attached disks and volumes for hot-plug polling. +pub fn device_snapshot() -> io::Result> { + let mut names = disk_interfaces()? + .into_iter() + .map(OsString::from) + .collect::>(); + let mut name = [0u16; MAX_PATH as usize + 1]; + // SAFETY: the buffer is writable for its stated length. + let find = unsafe { FindFirstVolumeW(name.as_mut_ptr(), name.len() as u32) }; + if find != INVALID_HANDLE_VALUE { + loop { + names.push(OsString::from(from_wide(&name))); + // SAFETY: `find` is live and the buffer writable. + if unsafe { FindNextVolumeW(find, name.as_mut_ptr(), name.len() as u32) } == 0 { + break; + } + } + // SAFETY: closes the search handle. + unsafe { FindVolumeClose(find) }; + } + names.sort_unstable(); + Ok(names) +} + +fn system_file(name: &str) -> bool { + let mut directory = [0u16; MAX_PATH as usize + 1]; + // SAFETY: the buffer is writable for its stated length. + let length = unsafe { GetWindowsDirectoryW(directory.as_mut_ptr(), directory.len() as u32) }; + length != 0 + && Path::new(&from_wide(&directory)) + .join("System32") + .join(name) + .is_file() +} + +fn unavailable(id: &str, explanation: &str) -> CapabilityState { + CapabilityState::Unavailable { + missing: vec![MissingRequirement { + id: id.to_owned(), + explanation: explanation.to_owned(), + remedy: None, + }], + } +} + +/// Windows capabilities: formatting uses the system's own file system +/// providers, and decoders, UEFI:NTFS, and boot records are built in. +pub(super) fn probe_capabilities() -> CapabilityReport { + let mut report = CapabilityReport::new(); + let formatter = if system_file("fmifs.dll") { + CapabilityState::Available + } else { + unavailable( + "fmifs.dll", + "the Windows format provider (fmifs.dll) is missing", + ) + }; + for capability in [ + Capability::FormatFat, + Capability::FormatFat32, + Capability::FormatExfat, + Capability::FormatNtfs, + Capability::FormatUdf, + ] { + report.set(capability, formatter.clone()); + } + for capability in [ + Capability::FormatExt2, + Capability::FormatExt3, + Capability::FormatExt4, + ] { + report.set( + capability, + unavailable( + "windows", + "ext2/3/4 creation is not available on Windows yet", + ), + ); + } + report.set( + Capability::FormatRefs, + unavailable( + "windows-edition", + "ReFS creation needs Windows Pro for Workstations or Enterprise and is not supported", + ), + ); + report.set(Capability::RawImageWrite, CapabilityState::Available); + report.set(Capability::CompressedImageWrite, CapabilityState::Available); + report.set( + Capability::VirtualDiskWrite, + if system_file("virtdisk.dll") { + CapabilityState::Available + } else { + unavailable( + "virtdisk.dll", + "the Windows virtual disk service is missing", + ) + }, + ); + report.set(Capability::IsoExtraction, CapabilityState::Available); + for capability in [ + Capability::ImageCaptureDd, + Capability::ImageCaptureVhd, + Capability::ImageCaptureVhdx, + ] { + report.set( + capability, + unavailable("capture", "drive capture is not implemented yet"), + ); + } + report.set( + Capability::ImageCaptureFfu, + unavailable("ffu", "FFU apply and capture are not implemented"), + ); + report.set( + Capability::FreeDos, + unavailable("assets/freedos", "FreeDOS assets not packaged yet"), + ); + report.set( + Capability::Syslinux, + unavailable("syslinux", "Syslinux installation is not available yet"), + ); + report.set( + Capability::Grub, + unavailable("grub", "GRUB installation is not available yet"), + ); + report.set(Capability::UefiNtfs, CapabilityState::Available); + report.set( + Capability::LinuxPersistence, + unavailable( + "persistence-layout", + "persistent partition creation is not implemented in this release", + ), + ); + report.set( + Capability::WindowsInstallerCustomization, + CapabilityState::Available, + ); + report.set( + Capability::WindowsToGo, + unavailable("experimental", "Windows To Go is not available yet"), + ); + report.set(Capability::WindowsIsoDownload, CapabilityState::Available); + report.set(Capability::UefiShellDownload, CapabilityState::Available); + report.set(Capability::ImageChecksums, CapabilityState::Available); + report.set( + Capability::UefiMediaValidation, + unavailable( + "uefi-validation-payload", + "verified UEFI validation payload is not packaged", + ), + ); + // The bad-block test is built into the disk engine. + report.set(Capability::BadBlocksCheck, CapabilityState::Available); + report +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_physical_drive_nodes() { + assert_eq!(disk_number(Path::new(r"\\.\PhysicalDrive3")), Some(3)); + assert_eq!(disk_number(Path::new(r"\\.\PhysicalDrive12")), Some(12)); + assert_eq!(disk_number(Path::new(r"\\.\PhysicalDrive")), None); + assert_eq!(disk_number(Path::new(r"\\.\PhysicalDrive1x")), None); + assert_eq!(disk_number(Path::new(r"C:\")), None); + assert_eq!(physical_drive_path(4), PathBuf::from(r"\\.\PhysicalDrive4")); + } + + fn volume(name: &str, disks: &[u32], mount: Option<&str>) -> Volume { + Volume { + name: format!(r"\\?\Volume{{{name}}}\"), + device: format!(r"\Device\HarddiskVolume-{name}"), + mount_points: mount.map(PathBuf::from).into_iter().collect(), + extents: disks + .iter() + .map(|disk| Extent { + disk: *disk, + offset: 1 << 20, + length: 1 << 30, + }) + .collect(), + } + } + + #[test] + fn volume_table_marks_system_and_mounted_disks() { + let volumes = [ + volume("os", &[0], Some(r"Z:\no-such-dir\")), + volume("esp", &[0], None), + volume("usb", &[2], Some(r"Y:\no-such-dir\")), + volume("span", &[3, 4], None), + ]; + let system = SystemVolumes { + windows: Some(volumes[0].name.clone()), + system_partition: Some(volumes[1].device.to_ascii_uppercase()), + }; + let os = volume_risks(0, &volumes, &system); + assert!(os.contains(&DeviceRisk::ContainsRoot)); + assert!(os.contains(&DeviceRisk::ContainsBoot)); + assert!(!os.contains(&DeviceRisk::MountedChildren)); + assert_eq!( + volume_risks(2, &volumes, &system), + [DeviceRisk::MountedChildren] + ); + assert_eq!( + volume_risks(3, &volumes, &system), + [DeviceRisk::ActiveVolumeMember] + ); + assert!(volume_risks(5, &volumes, &system).is_empty()); + } + + #[test] + fn descriptor_strings_are_trimmed_and_bounded() { + let mut bytes = vec![0u8; 64]; + bytes[40..48].copy_from_slice(b" Kingst"); + assert_eq!(descriptor_string(&bytes, 40), "Kingst"); + assert_eq!(descriptor_string(&bytes, 0), ""); + assert_eq!(descriptor_string(&bytes, 200), ""); + } + + #[test] + fn discovery_finds_and_protects_the_system_disk() { + // Enumeration needs no administrator rights, and every Windows host + // has the disk it runs from. + let devices = list_block_devices(true).expect("disk enumeration"); + for device in &devices { + assert!(device.node.is_absolute()); + assert!(device.fingerprint.canonical_sysfs_path.is_absolute()); + assert!(device.fingerprint.size_bytes > 0); + } + assert!( + devices + .iter() + .any(|device| device.has_risk(DeviceRisk::ContainsRoot)), + "the Windows disk must be marked: {devices:#?}" + ); + } +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b77ac13..32e2d4b 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -4,11 +4,11 @@ ### Desktop application -The Slint application owns presentation, localization, device summaries, image analysis, option validation, operation planning, and progress rendering. It runs as the logged-in user and opens a native Wayland or X11 window through Slint's platform backend. +The Slint application owns presentation, localization, device summaries, image analysis, option validation, operation planning, and progress rendering. It runs as the logged-in user, never elevated, and opens a native Wayland, X11, or Windows window through Slint's platform backend. ### Device service -The 0.1 device service reads `/sys/class/block`, `/sys/dev/block`, mountinfo, swap state and sysfs holder relationships. It records device ancestry rather than comparing only Linux major numbers. A lightweight watcher detects block-topology changes and coalesces automatic refreshes; manual refresh remains available. +On Linux, the device service reads `/sys/class/block`, `/sys/dev/block`, mountinfo, swap state and sysfs holder relationships. It records device ancestry rather than comparing only Linux major numbers. A lightweight watcher detects block-topology changes and coalesces automatic refreshes; manual refresh remains available. ### Image engine @@ -33,8 +33,23 @@ The planner converts a device snapshot, image report, and user options into an i the user. The system udisks2 daemon partitions, formats, mounts, and opens raw descriptors under its own polkit policy; the engine streams images, copies ISO files (via `rufust_image::isofs`), writes boot code, and verifies. Windows media -layout and boot records live in `rufust-helper/src/windows_media.rs`. This is -the default path and the only one that builds Windows media. +layout and boot records live in `rufust-helper/src/windows_media.rs`. On Linux +this is the default path and the only one that builds Windows media. + +### Windows engine + +On Windows the device service is `rufust-platform/src/windows.rs` (disk +interfaces, storage IOCTLs, and the volume table) and the engine is +`rufust_helper::execute` in `rufust-helper/src/windows/`. The desktop never +opens a disk: `helper_client/windows.rs` starts `rufust.exe --elevated-worker` +through UAC, and `rufust_helper::serve_pipe` in that elevated process reads +the same versioned request from a private named pipe and streams the same +events back. The engine locks and dismounts the target's volumes, partitions +with the disk IOCTLs, formats with Windows' `FormatEx` (or the built-in large +FAT32 formatter in `fat32.rs`), decodes compressed images in process, attaches +VHD/VHDX read-only, and reuses `windows_media.rs` for installer media. Progress +reporting and Windows-media planning shared with the udisks2 engine live in +`engine.rs`. See [Windows](WINDOWS.md). ### Privileged helper diff --git a/docs/BUILDING.md b/docs/BUILDING.md index aa2870d..39f67f6 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -88,7 +88,8 @@ The `packaging/` directory contains integration metadata and starter recipes: - `polkit/` — authorization policy for the narrow helper; - `tmpfiles/` — volatile root-owned runtime directory; - `debian/`, `rpm/`, `arch/` — distribution recipes; -- `appimage/` — AppImage staging, verification, launcher, and security notes. +- `appimage/` — AppImage staging, verification, launcher, and security notes; +- `windows/` — the README shipped in the Windows zip. Recipes intentionally do not download proprietary boot or Windows assets. Release builders must be reproducible, use Cargo's locked dependencies, generate a software bill of materials, and preserve license texts. @@ -137,3 +138,29 @@ The release workflow supplies SHA-verified appimagetool and type-2 runtime artifacts and embeds GitHub zsync update information. Do not stage the helper, polkit policy, setuid files, partitioning tools, formatters, glibc, or graphics drivers in the AppDir. The native package owns the privileged integration. + +## Windows + +Build on Windows 10/11 with the Rust MSVC toolchain (rustup) and Visual Studio +Build Tools with the "Desktop development with C++" workload. The Windows SDK +resource compiler embeds the original Rufus icon and the `asInvoker` manifest +into `rufust.exe`; `apps/rufust/build.rs` assembles the icon from +`assets/icons/`. No other system libraries or tools are needed: formatting +uses Windows' own providers, and decoders are linked in. + +```powershell +cargo build --release --locked -p rufust +cargo test --workspace --locked +cargo clippy --workspace --all-targets --locked -- -D warnings +``` + +From an elevated PowerShell, `scripts\windows\vhd-tests.ps1` runs the +end-to-end tests on throwaway VHDX disks (see [Windows](WINDOWS.md)). CI runs +the same steps on `windows-2022`. + +The release workflow's Windows job packages +`rufust--windows-x86_64.zip` with `rufust.exe`, +`packaging/windows/README.txt`, `LICENSE.txt`, and `THIRD_PARTY.md`. It checks +the reported version, the x86-64 PE machine, and the embedded `asInvoker` +manifest before the zip joins `SHA256SUMS` and the build provenance. Do not +ship a manifest that requests elevation: the window must stay unprivileged. diff --git a/docs/CAPABILITIES.md b/docs/CAPABILITIES.md index b8bb5b5..9c438a1 100644 --- a/docs/CAPABILITIES.md +++ b/docs/CAPABILITIES.md @@ -1,6 +1,6 @@ # Capability and compatibility matrix -Rufust preserves upstream concepts where Linux has a safe implementation. It does not claim that a visible option works until it can be completed end to end. **Available** means enabled in this release; **blocked** means the input is recognized but Start remains disabled with a reason; **planned** means no complete product flow exists yet. +Rufust preserves upstream concepts where each platform has a safe implementation. The tables first describe Linux; the [Windows](#windows) section lists what differs there. It does not claim that a visible option works until it can be completed end to end. **Available** means enabled in this release; **blocked** means the input is recognized but Start remains disabled with a reason; **planned** means no complete product flow exists yet. ## Available in 1.0 @@ -43,6 +43,42 @@ Rufust preserves upstream concepts where Linux has a safe implementation. It doe | UEFI runtime validation and Secure Boot revocation checks | Verified payload, SBAT/SVN/DBX parsing and signed update data are not packaged. | | Drive capture | Root must write through a user-opened file descriptor; arbitrary root-owned output paths are intentionally rejected. | +## Windows + +Windows 10 and 11 (x64) run the same interface, planner, protocol, and +Windows-media code; the platform layer is described in +[Windows](WINDOWS.md). Unless the table says otherwise, a capability above is +available on Windows with the same checks, and every Linux block below still +applies. + +| Capability | Windows implementation | Notes | +|---|---|---| +| Removable-device discovery | Disk interface enumeration and storage IOCTLs, without elevation | The disk holding Windows, the system partition, page files, mounted volumes, and spanned volumes are marked; virtual disks are never listed. Hot-plug polling of disks and volumes. | +| Authorized destructive operations | An elevated copy of `rufust.exe`, approved through UAC per operation and driven over private named pipes | The window never runs as administrator. Pipe clients must be the started worker. Target identity (interface path, disk number, size, sector size, serial, model) is resolved again before writing. | +| Exclusive access | Every target volume is locked and dismounted before raw I/O | A volume in use is retried, then force-dismounted; a volume that still cannot be locked stops the operation. | +| MBR/GPT/super-floppy formatting | `IOCTL_DISK_CREATE_DISK` / `SET_DRIVE_LAYOUT_EX` | Super floppy needs removable media, where Windows mounts a whole-disk volume. | +| FAT, FAT32, exFAT, NTFS, UDF | Windows' `fmifs.dll` `FormatEx`; FAT32 over 32 GB by a built-in formatter after upstream's `FormatLargeFAT32` | ext2/3/4 and ReFS are not offered on Windows. | +| Compressed raw images | In-process gzip, bzip2, xz, lzma, zstd, and single-file zip decoders | Capacity-bounded; decoding errors and size mismatches are fatal. Archives with several files are refused. | +| VHD/VHDX writing | Attached read-only through `virtdisk.dll` | Standalone images with 512-byte sectors; differencing disks are refused. The preview reads the capacity without elevation. | +| Windows installer media | Same layout and boot records | The MBR UEFI:NTFS partition becomes type 0xEF once its files are in. Copied files are read back after a dismount. | +| Bad-block test, verification, cancellation | Built into the engine | Cancellation is a `cancel` line on the control pipe or the window closing it. | +| Light and dark presentation | Same Slint workbench | Follows the Windows app mode; `%APPDATA%\Rufust\settings.conf`. | +| Portable desktop | `rufust--windows-x86_64.zip` | One executable with an `asInvoker` manifest; not code-signed yet. | + +Blocked only on Windows: ext2/3/4 creation (no Windows formatter) and ReFS +creation (only Pro for Workstations, Enterprise, and Server editions allow it, +through VDS). + +## Unreleased: Windows support + +Rufust now runs on Windows 10 and 11 (x64), alongside the Linux build, with +the capabilities in the [Windows](#windows) table. The window stays +unprivileged and each operation runs in an elevated copy of itself after one +UAC approval. Elevated tests on throwaway VHDX disks format with every +provider and scheme, write raw, gzip, and VHDX images with read-back +verification, build Windows installer media, run large FAT32, and cancel +through the worker pipes. Linux behavior is unchanged. + ## Changes in 1.1.0 Rufus Linux is renamed **Rufust**: the application, binaries (`rufust`, diff --git a/docs/PROJECT_CONTEXT.md b/docs/PROJECT_CONTEXT.md index 952e3fb..e312e19 100644 --- a/docs/PROJECT_CONTEXT.md +++ b/docs/PROJECT_CONTEXT.md @@ -8,14 +8,14 @@ and planned. ## Product identity -Rufust is an independent, Linux-native port inspired by +Rufust is an independent Linux and Windows port inspired by [Rufus](https://github.com/pbatard/rufus). It is not produced, endorsed, or supported by the upstream Rufus project. Preserve that disclaimer anywhere the name and original public-domain Rufus icon could imply official affiliation. The product target is a trustworthy USB device workbench for Arch Linux, -Debian/Ubuntu, and Fedora. Feature parity means implementing an upstream concept -safely on Linux; it does not mean exposing a control before its full operation +Debian/Ubuntu, Fedora, and Windows 10/11 (x64). Feature parity means +implementing an upstream concept safely on each platform; it does not mean exposing a control before its full operation is implemented and verified. ## Current baseline: 1.1.0 @@ -79,6 +79,37 @@ end-to-end implementation and its fixtures, integration tests, and boot tests exist. Supported standalone 512-byte-sector VHD/VHDX images convert when `qemu-nbd`, `nbdinfo`, and `nbdcopy` are installed. +## Windows support (unreleased, after 1.1.0) + +Rufust also runs on Windows 10 and 11 (x64). The UI, planner, helper +protocol, image analysis, Windows-media layout, answer files, and boot records +are shared; device discovery, privilege, and the disk engine are Windows +modules. Read [`WINDOWS.md`](WINDOWS.md) before changing them. In short: + +- the window stays unprivileged; each operation runs in an elevated copy of + `rufust.exe` (`--elevated-worker `), approved through UAC, that serves + one request over two private named pipes and accepts only its own process; +- discovery uses zero-access storage IOCTLs; the disk holding Windows, the + system partition, page files, spanned volumes, and virtual disks are + protected or hidden; +- the engine locks and dismounts the target's volumes, partitions with the + disk IOCTLs, formats with Windows' `FormatEx` plus a built-in large-FAT32 + formatter, decodes compressed images in process, and attaches VHD/VHDX + read-only through `virtdisk.dll`; +- ext2/3/4 and ReFS creation are not offered on Windows; everything else in + the Linux capability set is available there. + +Verification evidence: `cargo test` and `cargo clippy -D warnings` pass on +Windows; the elevated `scripts/windows/vhd-tests.ps1` passes on throwaway VHDX +disks (every provider and scheme, raw/gzip/VHDX writes with read-back, Windows +media for MBR BIOS+UEFI with UEFI:NTFS, GPT UEFI, and FAT32, large FAT32, and +the window's pipe launcher including cancellation); discovery and the VHD +capacity preview pass under a non-administrator token; and the release build +renders the workbench in the fixed 560x720 window. CI runs these on +`windows-2022`, and the release workflow adds +`rufust--windows-x86_64.zip`. No release containing Windows support +has been published yet; the next version bump publishes the first one. + ## Architecture map The user-facing flow is: @@ -117,6 +148,26 @@ Repository ownership is divided as follows: `.github/workflows/release.yml` builds and publishes all four installer formats. +On Windows the flow is the same with a different executor: + +```text +Slint UI (unprivileged user) + -> Windows disk discovery (zero-access IOCTLs) + -> the same plan and confirmation + -> one versioned request over private named pipes to + rufust.exe --elevated-worker, started through UAC per operation + -> structured progress, verification, flush, and exit +``` + +Windows ownership: `crates/rufust-platform/src/windows.rs` (discovery, volume +table, capabilities); `crates/rufust-helper/src/windows/` (engine, pipe +server, `FormatEx`, decoders, VHD attach, and the VHDX integration tests); +`crates/rufust-helper/src/fat32.rs` (large FAT32); `engine.rs` (progress and +Windows-media planning shared with udisks2); and in the app, +`helper_client/windows.rs` (UAC launch and pipes), `desktop.rs` (file chooser +and theme), plus Windows branches in `hotplug.rs`, `regional.rs`, +`settings.rs`, and `image_inspection.rs`. + Read [`ARCHITECTURE.md`](ARCHITECTURE.md) before moving responsibilities between modules or changing the operation state model. @@ -145,6 +196,11 @@ implementation details: - Keep external tools on reviewed absolute paths with cleared environments. Keep permissive udev rules, setuid launchers, direct `sudo` fallbacks, and a root GUI outside the design. +- On Windows, the window never runs as administrator and never opens a disk. + Only the UAC-elevated worker writes, after the same revalidation, and only + to a `\\.\PhysicalDriveN` whose interface path, number, size, sector size, + serial, and model still match. Every target volume stays locked and + dismounted during raw writes; the window's manifest stays `asInvoker`. ### AppImage trust boundary @@ -258,6 +314,10 @@ included in 0.1.3. These are known follow-ups, not claims that the current release is broken: +- Windows: smoke-test the zip on disposable physical USB media (flash drive + and USB SSD), boot-test Windows-built media, Authenticode-sign the + executable, and publish the first release that includes it. See + `WINDOWS.md`. - Run a packaged, real-polkit smoke test on disposable physical USB media for formatting, raw writing, Windows media, verification, cancellation, and disconnect during write. Automated tests, loop-backed udisks2 tests, and @@ -268,6 +328,7 @@ These are known follow-ups, not claims that the current release is broken: does not rewrite `boot.wim`, so the hardware bypass always uses upstream's `RunSynchronous` fallback from the root `autounattend.xml`. - Desktop theme startup currently uses `RUFUST_THEME` or `GTK_THEME`. + On Windows it uses `RUFUST_THEME` or the app-mode setting. Portal-backed system theme detection and persistence of a manual system/light/dark preference remain unimplemented. - `rufust-i18n` contains catalog groundwork but the Slint application still has @@ -312,6 +373,13 @@ cargo build --workspace --release --locked git diff --check ``` +On Windows, run the same `cargo fmt`, `cargo test`, `cargo clippy`, and +`cargo build --release` gates, then the elevated end-to-end tests: + +```powershell +powershell -ExecutionPolicy Bypass -File scripts/windows/vhd-tests.ps1 +``` + Changes to desktop metadata or authorization also require: ```sh @@ -321,7 +389,7 @@ xmllint --noout packaging/polkit/io.github.nitrodiesel.rufust.policy ``` The release workflow must produce one Debian package, RPM, Arch package, -AppImage, AppImage zsync file, and `SHA256SUMS`. The AppImage verifier must prove +AppImage, AppImage zsync file, Windows zip, and `SHA256SUMS`. The AppImage verifier must prove its architecture, glibc 2.28 ceiling, dependency closure, lack of RPATH, update information, metadata, executable permissions, unprivileged contents, direct version launch, extraction fallback, Xvfb GUI startup, and loader compatibility diff --git a/docs/SAFETY.md b/docs/SAFETY.md index a852974..89eb90b 100644 --- a/docs/SAFETY.md +++ b/docs/SAFETY.md @@ -1,6 +1,6 @@ # Safety and privilege model -The safety boundary is more important than feature parity. The desktop process must be usable without root privileges and must never gain ambient raw-disk access. +The safety boundary is more important than feature parity. The desktop process must be usable without root or administrator privileges and must never gain ambient raw-disk access. The sections below describe Linux; [Windows](#windows) keeps the same boundary with UAC. ## Process boundary @@ -110,3 +110,35 @@ require the root-owned `/usr/libexec/rufust-helper` and exact-path policy installed by a native package; the desktop checks file ownership, write permissions, policy content, and the effective registered action before launching `pkexec`. + +## Windows + +The same boundary holds on Windows, with UAC in place of polkit: + +```text +rufust.exe (user, unelevated) + -> discover disks with zero-access IOCTL queries + -> build the plan and show the target-specific confirmation + -> create two single-instance, local-only pipes with random names + -> start rufust.exe --elevated-worker with "runas" (UAC prompt) + -> accept only clients whose process ID is that worker's + -> send one request; render events; "cancel" or closing cancels + +Elevated worker (administrator, no window) + -> validate the typed request; refuse anything but \\.\PhysicalDriveN + -> open the source refusing links, deny other writers, recheck its size + -> refuse a source on the target; rediscover and compare the interface + path, disk number, size, sector size, serial, and model + -> refuse read-only targets and disks holding Windows, the system + partition, a page file, or part of a spanned volume + -> lock and dismount every target volume for the whole raw write + -> write, verify, flush, and exit +``` + +The window never runs elevated and never opens a disk; disk discovery opens +devices with no access rights. Each operation needs its own UAC approval, and +declining writes nothing. Virtual disks are never listed as targets. The +worker runs the bytes of the executable the user started, as upstream Rufus +does; Authenticode signing of releases is an open gate. Compressed images are +decoded in the elevated worker, so only memory-safe Rust decoders are used +there. Formatting uses Windows' own file system providers. diff --git a/docs/WINDOWS.md b/docs/WINDOWS.md new file mode 100644 index 0000000..c3cede0 --- /dev/null +++ b/docs/WINDOWS.md @@ -0,0 +1,149 @@ +# Windows + +Rufust runs natively on Windows 10 and 11 (x64) with the same interface, +operation planner, helper protocol, Windows-media layout, and safety checks as +on Linux. Only the platform layer differs: device discovery, privilege, and +the disk engine. Read this before changing anything under a `windows` module. + +## Privilege model + +The window never runs as administrator, mirroring the unprivileged desktop on +Linux. Writing to `\\.\PhysicalDriveN` needs administrator rights, so each +operation runs in a separate elevated worker: + +```text +rufust.exe (unelevated window) + -> discover disks with zero-access IOCTL queries + -> build and confirm the same immutable plan as on Linux + -> create two single-instance, local-only named pipes + \\.\pipe\rufust---control (window writes) + \\.\pipe\rufust---events (window reads) + -> ShellExecuteEx "runas": rufust.exe --elevated-worker (one UAC prompt) + -> accept the pipe clients only if their process ID is that worker's + -> send one NDJSON HelperRequest; render HelperEvents + +rufust.exe --elevated-worker (elevated, no window) + -> validate the request (rufust_helper::serve_pipe -> execute) + -> bind the source, revalidate the target, lock and dismount its volumes + -> partition, format, write, copy, verify, flush + -> stream events; a "cancel" line or a closed control pipe cancels +``` + +The worker is the desktop executable itself, so the portable download is one +file, like upstream Rufus. `rufust-helper.exe --execute-pipe ` serves the +same pipes and is what the automated tests launch. Declining UAC writes +nothing. Pipe names accept only letters, digits, and `-`. + +## Device discovery and identity + +`rufust-platform/src/windows.rs` enumerates `GUID_DEVINTERFACE_DISK` and +queries each disk with `IOCTL_STORAGE_GET_DEVICE_NUMBER`, +`IOCTL_STORAGE_QUERY_PROPERTY`, `IOCTL_DISK_GET_DRIVE_GEOMETRY_EX`, and +`IOCTL_DISK_IS_WRITABLE`, opening it with no access rights so no elevation is +needed. In `DeviceIdentity`: + +| Field | Windows meaning | +|---|---| +| `node` | `\\.\PhysicalDriveN` (a display name, not identity) | +| `sysfs_path` | the device interface path, which embeds the PnP instance ID | +| `major` / `minor` | `0` / the disk number | +| `transport` | from `STORAGE_BUS_TYPE`; file-backed and virtual disks are `loop` | + +The volume table (`FindFirstVolume`, `IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS`) +marks the disk holding the Windows directory (`ContainsRoot`), the system +partition named in `HKLM\SYSTEM\Setup` (`ContainsBoot`), a page or swap file +(`ContainsSwap`), mounted volumes (`MountedChildren`), and volumes spanning +several disks (`ActiveVolumeMember`). Virtual disks (attached VHDs) are never +listed, like Linux loop devices. Hot-plug polls disk interfaces and volume +names twice a second. + +## Disk engine + +`rufust-helper/src/windows/` mirrors the udisks2 engine step for step: + +- **Revalidation.** The worker rediscovers the disk and compares the + interface path, disk number, size, sector size, serial, and model, then + refuses read-only media and every blocking risk above. The source must not + live on a volume of the target. +- **Exclusive access.** Every volume on the target is locked + (`FSCTL_LOCK_VOLUME`, retried, then forced) and dismounted before raw I/O, + and stays locked until the write is done. Boot records are written through + the locked, still-mounted volume, as upstream does. +- **Partitioning.** `IOCTL_DISK_CREATE_DISK` and + `IOCTL_DISK_SET_DRIVE_LAYOUT_EX` after zeroing the first and last MiB. New + volumes are found by their extent on the target disk, never by drive letter; + their letters are removed while formatting (so Explorer does not offer to + format them) and one is assigned when the job finishes. +- **File systems.** FAT, FAT32, exFAT, NTFS, and UDF come from Windows' own + provider (`fmifs.dll` `FormatEx`). FAT32 over 32 GB, which Windows refuses, + uses a built-in formatter ported from upstream's `FormatLargeFAT32` + (`rufust-helper/src/fat32.rs`). ext2/3/4 and ReFS are not offered. +- **Images.** Raw and ISOHybrid images are copied in whole sectors (the final + sector is zero-padded). gzip, bzip2, xz, lzma, zstd, and single-file zip + images are decoded in process by memory-safe Rust decoders. Standalone + 512-byte-sector VHD/VHDX images are attached read-only through + `virtdisk.dll` and copied from their disk; differencing disks are refused. +- **Windows installer media.** The shared `windows_media.rs` layout, copy, + customization, and boot-record code. On MBR, the UEFI:NTFS partition is + created as FAT12 for its files and switched to type 0xEF afterwards. +- **Verification.** Image writes are read back from the disk and hashed; + copied files are read back after a dismount so the cache is not trusted. + +The desktop's VHD/VHDX capacity preview uses `OpenVirtualDisk` with +get-info access, which needs no elevation. + +## Desktop integration + +- File chooser: the common Open dialog, owned by the workbench window. +- Theme: `RUFUST_THEME`, else the "app mode" (`AppsUseLightTheme`) setting. +- Settings: `%APPDATA%\Rufust\settings.conf`. +- Regional options for the Windows User Experience dialog: the system and user + locales, display language, keyboard layout, and time zone key name, read + from Windows as upstream does. +- `rufust.exe` embeds the original Rufus icon and an `asInvoker` manifest + (per-monitor DPI aware, common controls 6). Release builds use the GUI + subsystem; `--version` still prints when output is redirected. + +## Building + +Install Rust with rustup and the MSVC toolchain (Visual Studio Build Tools +with the "Desktop development with C++" workload, which includes the Windows +SDK resource compiler). No other system libraries are needed. + +```powershell +cargo build --release -p rufust +target\release\rufust.exe +``` + +`cargo test --workspace` and `cargo clippy --workspace --all-targets -- -D +warnings` run unelevated. The end-to-end tests need an elevated PowerShell; +they create and attach throwaway VHDX disks and refuse every disk that is not +file-backed virtual storage: + +```powershell +powershell -ExecutionPolicy Bypass -File scripts\windows\vhd-tests.ps1 +``` + +They format with every provider and scheme, write raw, gzip, and VHDX images +with read-back verification, build Windows installer media (MBR BIOS+UEFI with +UEFI:NTFS, GPT UEFI, FAT32) from a synthetic ISO, run large FAT32 on a sparse +40 GiB disk, and drive the window's pipe launcher through a format and a +cancellation. CI runs them on every push. + +## Packaging + +The release workflow builds `rufust--windows-x86_64.zip` containing +`rufust.exe`, `README.txt` (from `packaging/windows/`), `LICENSE.txt`, and +`THIRD_PARTY.md`, checks the PE machine and the `asInvoker` manifest, and adds +it to `SHA256SUMS` and the build provenance. The executable is not +Authenticode-signed yet, so SmartScreen may warn on first launch. + +## Open gates + +- A smoke test on disposable physical USB media (flash drive and USB SSD): + format, image write, Windows media, verification, cancellation, and + unplugging during a write. Virtual disks do not replace it. +- Boot tests of Windows-built media in QEMU/OVMF and on hardware. +- Authenticode signing of release executables. +- ext2/3/4 and ReFS creation, drive capture, and the other features blocked + on Linux remain blocked here. diff --git a/packaging/windows/README.txt b/packaging/windows/README.txt new file mode 100644 index 0000000..ee39553 --- /dev/null +++ b/packaging/windows/README.txt @@ -0,0 +1,38 @@ +Rufust for Windows +================== + +Rufust is an independent, community-built Linux and Windows port inspired by +Rufus. It is not produced, endorsed, or supported by the upstream Rufus +project or its maintainers. + +Run rufust.exe. Nothing is installed. Windows 10 or 11 (x64) is required. + +The window runs with your normal rights. When you press Start and confirm, +Windows asks once for administrator approval for that operation only; the +disk work runs in a separate elevated copy of rufust.exe. Declining writes +nothing. + +WARNING: writing or formatting permanently destroys the data on the selected +drive. Rufust hides system disks and most USB hard disks by default, checks +the drive again just before writing, and names it in the confirmation. + +Rufust can: + - write raw, ISOHybrid, compressed (.gz, .bz2, .xz, .lzma, .zst, .zip) and + VHD/VHDX disk images, with read-back verification; + - create Windows 10/11 installer drives from Windows ISOs (NTFS with the + signed UEFI:NTFS boot partition, exFAT, or FAT32), including the Windows + User Experience options; + - format drives as FAT, FAT32 (any size), exFAT, NTFS, or UDF, with an + optional bad-block test. + +Settings are kept in %APPDATA%\Rufust\settings.conf. + +The executable is not code-signed yet, so Windows SmartScreen may ask you to +confirm the first launch. Verify the download against SHA256SUMS from the +release page: + + Get-FileHash .\rufust-*-windows-x86_64.zip -Algorithm SHA256 + +Source, documentation, and issues: https://github.com/NitroDiesel/rufust +License: GNU General Public License version 3 (LICENSE.txt). Third-party +notices: THIRD_PARTY.md. diff --git a/scripts/windows/vhd-tests.ps1 b/scripts/windows/vhd-tests.ps1 new file mode 100644 index 0000000..e4d5e40 --- /dev/null +++ b/scripts/windows/vhd-tests.ps1 @@ -0,0 +1,81 @@ +# End-to-end tests of the Windows disk engine on disposable virtual disks. +# +# Run from an elevated PowerShell at the repository root: +# powershell -ExecutionPolicy Bypass -File scripts\windows\vhd-tests.ps1 +# +# Creates a 2 GiB and a sparse 40 GiB VHDX in a temporary folder and attaches +# them, plus a detached 16 MiB VHDX used as a source image. It runs the +# ignored `windows::vhd_tests` (helper engine) and the desktop's worker-pipe +# and VHD preview tests, then detaches and deletes everything. The tests +# refuse any disk that is not file-backed virtual storage. + +$ErrorActionPreference = 'Stop' + +$principal = New-Object Security.Principal.WindowsPrincipal( + [Security.Principal.WindowsIdentity]::GetCurrent()) +if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + throw 'Run this script from an elevated (administrator) PowerShell.' +} + +$work = Join-Path ([IO.Path]::GetTempPath()) ("rufust-vhd-" + [Guid]::NewGuid()) +New-Item -ItemType Directory -Path $work | Out-Null +$small = Join-Path $work 'small.vhdx' +$large = Join-Path $work 'large.vhdx' +$source = Join-Path $work 'source.vhdx' + +function Invoke-DiskPart([string[]] $commands) { + $script = Join-Path $work 'diskpart.txt' + Set-Content -Path $script -Value $commands -Encoding ascii + $output = & diskpart.exe /s $script + if ($LASTEXITCODE -ne 0) { + throw "diskpart failed:`n$($output -join "`n")" + } +} + +function Mount-TestDisk([string] $path, [int] $megabytes) { + Invoke-DiskPart @( + "create vdisk file=`"$path`" maximum=$megabytes type=expandable", + "select vdisk file=`"$path`"", + 'attach vdisk' + ) + for ($attempt = 0; $attempt -lt 40; $attempt++) { + $number = (Get-DiskImage -ImagePath $path).Number + if ($null -ne $number) { + return $number + } + Start-Sleep -Milliseconds 250 + } + throw "Windows did not report a disk number for $path" +} + +try { + $env:RUFUST_TEST_DISK = Mount-TestDisk $small 2048 + $env:RUFUST_TEST_LARGE_DISK = Mount-TestDisk $large 40960 + Invoke-DiskPart @("create vdisk file=`"$source`" maximum=16 type=fixed") + $env:RUFUST_TEST_VHD_SOURCE = $source + Write-Host "Testing on disk $env:RUFUST_TEST_DISK and large disk $env:RUFUST_TEST_LARGE_DISK" + cargo build -p rufust-helper --locked + cargo test -p rufust-helper --locked windows::vhd_tests -- --ignored --test-threads=1 + if ($LASTEXITCODE -ne 0) { + throw 'virtual disk tests failed' + } + cargo test -p rufust --locked -- --ignored --test-threads=1 helper_client::windows::tests image_inspection::windows_tests + if ($LASTEXITCODE -ne 0) { + throw 'worker pipe tests failed' + } +} +finally { + foreach ($path in @($small, $large)) { + if (Test-Path $path) { + try { + Invoke-DiskPart @("select vdisk file=`"$path`"", 'detach vdisk') + } + catch { + Write-Warning "Could not detach ${path}: $_" + } + } + } + Remove-Item -Recurse -Force $work -ErrorAction SilentlyContinue + Remove-Item Env:\RUFUST_TEST_DISK -ErrorAction SilentlyContinue + Remove-Item Env:\RUFUST_TEST_LARGE_DISK -ErrorAction SilentlyContinue +} From 64748dba621b50f18b9a21df8e89b1ad61c9a898 Mon Sep 17 00:00:00 2001 From: NitroDiesel <228459919+NitroDiesel@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:21:21 +0800 Subject: [PATCH 2/3] Add a Windows installer to releases The release workflow now compiles packaging/windows/rufust.iss with Inno Setup into rufust--windows-x86_64-setup.exe next to the portable zip. Setup installs per machine into Program Files with a Start menu entry and uninstaller, launches the app as the original user (never elevated), and is verified in CI by a silent install and uninstall. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 55 ++++++++++++++++++++++++++++++-- README.md | 12 ++++--- docs/BUILDING.md | 12 +++++++ docs/CAPABILITIES.md | 5 ++- docs/PROJECT_CONTEXT.md | 4 ++- docs/SAFETY.md | 4 ++- docs/WINDOWS.md | 23 +++++++++++--- packaging/windows/README.txt | 6 ++-- packaging/windows/rufust.iss | 60 +++++++++++++++++++++++++++++++++++ 9 files changed, 164 insertions(+), 17 deletions(-) create mode 100644 packaging/windows/rufust.iss diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d7f280b..4b6e38b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -296,7 +296,7 @@ jobs: if-no-files-found: error windows: - name: Windows portable build + name: Windows installer and portable build runs-on: windows-2022 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 @@ -321,10 +321,58 @@ jobs: $text = [Text.Encoding]::ASCII.GetString($bytes) if (-not $text.Contains('level="asInvoker"')) { throw 'missing asInvoker manifest' } Compress-Archive -Path $name -DestinationPath "dist\$name.zip" + - name: Build installer + shell: pwsh + run: | + $iscc = "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe" + if (-not (Test-Path $iscc)) { + choco install innosetup --yes --no-progress + if ($LASTEXITCODE -ne 0) { throw 'could not install Inno Setup' } + } + $icon = Get-ChildItem target\release\build\rufust-*\out\rufust.ico | + Select-Object -First 1 + if (-not $icon) { throw 'build did not produce rufust.ico' } + & $iscc /Q "/DVersion=$env:PACKAGE_VERSION" "/DIconFile=$($icon.FullName)" ` + packaging\windows\rufust.iss + if ($LASTEXITCODE -ne 0) { throw "ISCC failed with $LASTEXITCODE" } + - name: Install and uninstall the installer + shell: pwsh + run: | + $setup = "dist\rufust-$env:PACKAGE_VERSION-windows-x86_64-setup.exe" + $dir = Join-Path $env:RUNNER_TEMP 'Rufust' + $silent = '/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART' + $run = Start-Process $setup -ArgumentList ($silent + "/DIR=$dir") -Wait -PassThru + if ($run.ExitCode -ne 0) { throw "setup exited with $($run.ExitCode)" } + foreach ($file in 'rufust.exe', 'README.txt', 'LICENSE.txt', 'THIRD_PARTY.md') { + if (-not (Test-Path "$dir\$file")) { throw "missing $file" } + } + if ((Get-FileHash "$dir\rufust.exe").Hash -ne + (Get-FileHash target\release\rufust.exe).Hash) { + throw 'installed rufust.exe differs from the build' + } + $version = & "$dir\rufust.exe" --version | Out-String + if ($version.Trim() -ne "rufust $env:PACKAGE_VERSION") { + throw "unexpected version: $version" + } + $shortcut = "$env:ProgramData\Microsoft\Windows\Start Menu\Programs\Rufust.lnk" + if (-not (Test-Path $shortcut)) { throw 'missing Start menu shortcut' } + $key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{6C1F3B0E-7D2A-4E59-9B8C-2F4A1D7E5C31}_is1' + if ((Get-ItemProperty $key).DisplayVersion -ne $env:PACKAGE_VERSION) { + throw 'missing or wrong uninstall entry' + } + $run = Start-Process "$dir\unins000.exe" -ArgumentList $silent -Wait -PassThru + if ($run.ExitCode -ne 0) { throw "uninstall exited with $($run.ExitCode)" } + # The uninstaller removes its own files from a child process. + for ($i = 0; $i -lt 40 -and (Test-Path $dir); $i++) { Start-Sleep -Milliseconds 250 } + if ((Test-Path $dir) -or (Test-Path $shortcut) -or (Test-Path $key)) { + throw 'uninstall left files, shortcut or registry entry behind' + } - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: name: installer-windows - path: dist/*.zip + path: | + dist/*.zip + dist/*-setup.exe if-no-files-found: error publish: @@ -380,7 +428,8 @@ jobs: - Fedora: `sudo dnf install ./rufust-*.x86_64.rpm` - Arch Linux: `sudo pacman -U ./rufust-*-x86_64.pkg.tar.zst` - Portable desktop: `chmod +x ./rufust-*.AppImage && ./rufust-*.AppImage` - - Windows 10/11 (x64): extract `rufust-*-windows-x86_64.zip` and run + - Windows 10/11 (x64): run `rufust-*-windows-x86_64-setup.exe`, or + extract the portable `rufust-*-windows-x86_64.zip` and run `rufust.exe`; Windows asks for administrator approval at Start. The AppImage runs on x86_64 glibc 2.28+ desktops. If FUSE is not diff --git a/README.md b/README.md index 26e5c90..337aece 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ The goal is output compatibility where each platform has a safe, maintained impl - Native Slint desktop interface on Wayland, X11, and Windows, with light and dark themes that follow the system. - Automatic sysfs-backed device discovery with mount and device-holder safety checks. - Plug and play: writes go through the system udisks2 service, so nothing extra has to be installed. A small polkit-authorized helper is the fallback. -- On Windows: a single portable `rufust.exe`. The window stays unprivileged; each operation runs in an elevated worker after one UAC approval, using Windows' own partitioning and file system providers plus a built-in large-FAT32 formatter. +- On Windows: an installer or a single portable `rufust.exe`. The window stays unprivileged; each operation runs in an elevated worker after one UAC approval, using Windows' own partitioning and file system providers plus a built-in large-FAT32 formatter. - MBR/GPT partitioning, raw image writing, verification, and common Linux/portable filesystems. - ISO/ISOHybrid and compressed-image analysis with clear compatibility and safety feedback. - Logged, cancellable operations with a final flush before a device is reported ready. @@ -126,11 +126,15 @@ release is stable within its documented capability set; review the ### Windows -Download `rufust-*-windows-x86_64.zip` (Windows 10/11, x64), check it against -`SHA256SUMS`, extract it, and run `rufust.exe`. Nothing is installed. +For Windows 10/11 (x64), pick one download and check it against `SHA256SUMS`: + +- **Installer:** `rufust-*-windows-x86_64-setup.exe` installs Rufust in + Program Files with a Start menu entry and an uninstaller (Settings → Apps). +- **Portable:** extract `rufust-*-windows-x86_64.zip` and run `rufust.exe`. + Nothing is installed. ```powershell -Get-FileHash .\rufust-*-windows-x86_64.zip -Algorithm SHA256 +Get-FileHash .\rufust-*-windows-x86_64* -Algorithm SHA256 ``` The window runs with your normal rights. When you confirm an operation, diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 39f67f6..29b7a31 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -164,3 +164,15 @@ The release workflow's Windows job packages the reported version, the x86-64 PE machine, and the embedded `asInvoker` manifest before the zip joins `SHA256SUMS` and the build provenance. Do not ship a manifest that requests elevation: the window must stay unprivileged. + +The same job compiles `packaging/windows/rufust.iss` with Inno Setup 6 into +`rufust--windows-x86_64-setup.exe`, then installs it silently, checks +the installed files, Start menu entry, and uninstall entry, and uninstalls it +again. To build the installer yourself after the release build: + +```powershell +$icon = (Get-ChildItem target\release\build\rufust-*\out\rufust.ico)[0].FullName +& "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe" /DVersion=1.1.0 "/DIconFile=$icon" packaging\windows\rufust.iss +``` + +The installer lands in `dist\`. diff --git a/docs/CAPABILITIES.md b/docs/CAPABILITIES.md index 9c438a1..80d639c 100644 --- a/docs/CAPABILITIES.md +++ b/docs/CAPABILITIES.md @@ -63,6 +63,7 @@ applies. | Windows installer media | Same layout and boot records | The MBR UEFI:NTFS partition becomes type 0xEF once its files are in. Copied files are read back after a dismount. | | Bad-block test, verification, cancellation | Built into the engine | Cancellation is a `cancel` line on the control pipe or the window closing it. | | Light and dark presentation | Same Slint workbench | Follows the Windows app mode; `%APPDATA%\Rufust\settings.conf`. | +| Installer | `rufust--windows-x86_64-setup.exe` (Inno Setup) | Per-machine install into Program Files with a Start menu entry and uninstaller; not code-signed yet. | | Portable desktop | `rufust--windows-x86_64.zip` | One executable with an `asInvoker` manifest; not code-signed yet. | Blocked only on Windows: ext2/3/4 creation (no Windows formatter) and ReFS @@ -77,7 +78,9 @@ unprivileged and each operation runs in an elevated copy of itself after one UAC approval. Elevated tests on throwaway VHDX disks format with every provider and scheme, write raw, gzip, and VHDX images with read-back verification, build Windows installer media, run large FAT32, and cancel -through the worker pipes. Linux behavior is unchanged. +through the worker pipes. Releases include a Windows installer +(`rufust--windows-x86_64-setup.exe`) and a portable zip. Linux +behavior is unchanged. ## Changes in 1.1.0 diff --git a/docs/PROJECT_CONTEXT.md b/docs/PROJECT_CONTEXT.md index e312e19..cd7a200 100644 --- a/docs/PROJECT_CONTEXT.md +++ b/docs/PROJECT_CONTEXT.md @@ -107,7 +107,9 @@ the window's pipe launcher including cancellation); discovery and the VHD capacity preview pass under a non-administrator token; and the release build renders the workbench in the fixed 560x720 window. CI runs these on `windows-2022`, and the release workflow adds -`rufust--windows-x86_64.zip`. No release containing Windows support +`rufust--windows-x86_64-setup.exe` (Inno Setup, verified by a silent +install and uninstall) and the portable `rufust--windows-x86_64.zip`. +No release containing Windows support has been published yet; the next version bump publishes the first one. ## Architecture map diff --git a/docs/SAFETY.md b/docs/SAFETY.md index 89eb90b..6eb7de1 100644 --- a/docs/SAFETY.md +++ b/docs/SAFETY.md @@ -139,6 +139,8 @@ The window never runs elevated and never opens a disk; disk discovery opens devices with no access rights. Each operation needs its own UAC approval, and declining writes nothing. Virtual disks are never listed as targets. The worker runs the bytes of the executable the user started, as upstream Rufus -does; Authenticode signing of releases is an open gate. Compressed images are +does. The installer puts that executable in Program Files, where only +administrators can replace it, and starts the app after setup as the original +user, never elevated. Authenticode signing of releases is an open gate. Compressed images are decoded in the elevated worker, so only memory-safe Rust decoders are used there. Formatting uses Windows' own file system providers. diff --git a/docs/WINDOWS.md b/docs/WINDOWS.md index c3cede0..117955d 100644 --- a/docs/WINDOWS.md +++ b/docs/WINDOWS.md @@ -30,7 +30,7 @@ rufust.exe --elevated-worker (elevated, no window) ``` The worker is the desktop executable itself, so the portable download is one -file, like upstream Rufus. `rufust-helper.exe --execute-pipe ` serves the +file, like upstream Rufus, and the installer installs just that file. `rufust-helper.exe --execute-pipe ` serves the same pipes and is what the automated tests launch. Declining UAC writes nothing. Pipe names accept only letters, digits, and `-`. @@ -132,10 +132,23 @@ cancellation. CI runs them on every push. ## Packaging -The release workflow builds `rufust--windows-x86_64.zip` containing +The release workflow builds two downloads with the same four files: `rufust.exe`, `README.txt` (from `packaging/windows/`), `LICENSE.txt`, and -`THIRD_PARTY.md`, checks the PE machine and the `asInvoker` manifest, and adds -it to `SHA256SUMS` and the build provenance. The executable is not +`THIRD_PARTY.md`. + +- `rufust--windows-x86_64.zip`: portable, nothing installed. +- `rufust--windows-x86_64-setup.exe`: an Inno Setup installer + (`packaging/windows/rufust.iss`). It installs per machine into Program Files + with a Start menu entry, an optional desktop icon, and an uninstaller. + Because only administrators can write to Program Files, a standard user + cannot replace the executable that the elevated worker runs. Setup itself + is elevated, so its "Launch Rufust" option starts the app as the original + user (`runasoriginaluser`); the window never runs elevated. Uninstalling + keeps `%APPDATA%\Rufust\settings.conf`. + +The job checks the PE machine and the `asInvoker` manifest, installs and +uninstalls the installer silently, and adds both files to `SHA256SUMS` and the +build provenance. Neither the executable nor the installer is Authenticode-signed yet, so SmartScreen may warn on first launch. ## Open gates @@ -144,6 +157,6 @@ Authenticode-signed yet, so SmartScreen may warn on first launch. format, image write, Windows media, verification, cancellation, and unplugging during a write. Virtual disks do not replace it. - Boot tests of Windows-built media in QEMU/OVMF and on hardware. -- Authenticode signing of release executables. +- Authenticode signing of release executables and the installer. - ext2/3/4 and ReFS creation, drive capture, and the other features blocked on Linux remain blocked here. diff --git a/packaging/windows/README.txt b/packaging/windows/README.txt index ee39553..237c103 100644 --- a/packaging/windows/README.txt +++ b/packaging/windows/README.txt @@ -5,7 +5,9 @@ Rufust is an independent, community-built Linux and Windows port inspired by Rufus. It is not produced, endorsed, or supported by the upstream Rufus project or its maintainers. -Run rufust.exe. Nothing is installed. Windows 10 or 11 (x64) is required. +Windows 10 or 11 (x64) is required. The installer puts rufust.exe in +Program Files with a Start menu entry; remove it from Settings > Apps. The +portable zip installs nothing: extract it and run rufust.exe. The window runs with your normal rights. When you press Start and confirm, Windows asks once for administrator approval for that operation only; the @@ -31,7 +33,7 @@ The executable is not code-signed yet, so Windows SmartScreen may ask you to confirm the first launch. Verify the download against SHA256SUMS from the release page: - Get-FileHash .\rufust-*-windows-x86_64.zip -Algorithm SHA256 + Get-FileHash .\rufust-*-windows-x86_64* -Algorithm SHA256 Source, documentation, and issues: https://github.com/NitroDiesel/rufust License: GNU General Public License version 3 (LICENSE.txt). Third-party diff --git a/packaging/windows/rufust.iss b/packaging/windows/rufust.iss new file mode 100644 index 0000000..f71db22 --- /dev/null +++ b/packaging/windows/rufust.iss @@ -0,0 +1,60 @@ +; Inno Setup script for the Rufust Windows installer. +; +; Build from the repository root after `cargo build -p rufust --release`: +; iscc /DVersion=1.1.0 /DIconFile= packaging\windows\rufust.iss +; +; The installer writes to Program Files, so only administrators can replace +; the executable that the elevated disk worker runs. The app itself keeps its +; asInvoker manifest and is always started unelevated, also after setup. + +#ifndef Version + #error Pass the version with /DVersion=x.y.z +#endif +#define Root "..\.." + +[Setup] +AppId={{6C1F3B0E-7D2A-4E59-9B8C-2F4A1D7E5C31} +AppName=Rufust +AppVersion={#Version} +AppVerName=Rufust {#Version} +AppPublisher=Rufust contributors +AppPublisherURL=https://github.com/NitroDiesel/rufust +AppSupportURL=https://github.com/NitroDiesel/rufust/issues +AppUpdatesURL=https://github.com/NitroDiesel/rufust/releases +VersionInfoVersion={#Version} +DefaultDirName={autopf}\Rufust +DefaultGroupName=Rufust +DisableProgramGroupPage=yes +PrivilegesRequired=admin +ArchitecturesAllowed=x64compatible +ArchitecturesInstallIn64BitMode=x64compatible +MinVersion=10.0 +LicenseFile={#Root}\LICENSE.txt +OutputDir={#Root}\dist +OutputBaseFilename=rufust-{#Version}-windows-x86_64-setup +#ifdef IconFile +SetupIconFile={#IconFile} +#endif +UninstallDisplayIcon={app}\rufust.exe +UninstallDisplayName=Rufust +Compression=lzma2/max +SolidCompression=yes +WizardStyle=modern +CloseApplications=yes + +[Tasks] +Name: desktopicon; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked + +[Files] +Source: "{#Root}\target\release\rufust.exe"; DestDir: "{app}"; Flags: ignoreversion +Source: "{#Root}\packaging\windows\README.txt"; DestDir: "{app}"; Flags: ignoreversion +Source: "{#Root}\LICENSE.txt"; DestDir: "{app}"; Flags: ignoreversion +Source: "{#Root}\THIRD_PARTY.md"; DestDir: "{app}"; Flags: ignoreversion + +[Icons] +Name: "{autoprograms}\Rufust"; Filename: "{app}\rufust.exe" +Name: "{autodesktop}\Rufust"; Filename: "{app}\rufust.exe"; Tasks: desktopicon + +[Run] +; runasoriginaluser: setup is elevated, but the window must never be. +Filename: "{app}\rufust.exe"; Description: "{cm:LaunchProgram,Rufust}"; Flags: nowait postinstall skipifsilent runasoriginaluser From 02cce6c0c250e251a81a0f71d2a3ff9c2e80c646 Mon Sep 17 00:00:00 2001 From: NitroDiesel <228459919+NitroDiesel@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:54:24 +0800 Subject: [PATCH 3/3] Release as 1.2.0 1.2.0 is the first release with Windows 10 and 11 support: an installer and a portable zip next to the Linux packages and AppImage. Bump the workspace, app, and package versions, add the Debian, RPM, and AppStream changelog entries, and update the release notes and project context. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 21 +++++++++-------- Cargo.lock | 18 +++++++-------- Cargo.toml | 2 +- README.md | 2 +- apps/rufust/ui/appwindow.slint | 2 +- docs/BUILDING.md | 4 ++-- docs/CAPABILITIES.md | 2 +- docs/PROJECT_CONTEXT.md | 23 +++++++++---------- packaging/arch/PKGBUILD | 2 +- packaging/debian/changelog | 6 +++++ .../io.github.nitrodiesel.rufust.metainfo.xml | 6 +++++ packaging/rpm/rufust.spec | 5 +++- packaging/windows/rufust.iss | 2 +- 13 files changed, 56 insertions(+), 39 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4b6e38b..9ed0e56 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,7 +20,7 @@ permissions: env: CARGO_TERM_COLOR: always - PACKAGE_VERSION: 1.1.0 + PACKAGE_VERSION: 1.2.0 jobs: debian: @@ -417,12 +417,14 @@ jobs: capability set. It is an independent port and is not produced, endorsed, or supported by the upstream Rufus project. - Highlights: automatic USB hot-plug detection, aligned and - keyboard-accessible controls, a continuous Windows-style progress - bar, true modal overlays, and stronger privileged source/target - validation with cooperative cancellation. + New in 1.2.0: Rufust runs on Windows 10 and 11 (x64), with an + installer and a portable download. The window stays unprivileged; + each operation runs in an elevated worker after one UAC approval. + On Windows, ext2/3/4 and ReFS creation are not offered. The Windows + downloads are not code-signed yet, so SmartScreen may ask you to + confirm the first launch. Linux behavior is unchanged. - Download the package for your x86_64 distribution: + Download the package for your x86_64 system: - Debian/Ubuntu: `sudo apt install ./rufust_*_amd64.deb` - Fedora: `sudo dnf install ./rufust-*.x86_64.rpm` @@ -434,14 +436,15 @@ jobs: The AppImage runs on x86_64 glibc 2.28+ desktops. If FUSE is not available, add `--appimage-extract-and-run`. For security, the - portable artifact does not contain privileged code: writing and + AppImage does not contain privileged code: writing and formatting require the matching native package's root-owned helper. - Verify the download first with `sha256sum -c SHA256SUMS`. + Verify the download first with `sha256sum -c SHA256SUMS` (on + Windows, compare `Get-FileHash` with the matching line). This release supports safe formatting and raw, compressed-raw, ISOHybrid, and standalone VHD/VHDX writing with verification. - Native packages install qemu-nbd, nbdinfo, and nbdcopy for + Linux native packages install qemu-nbd, nbdinfo, and nbdcopy for conversion. Review the project capability matrix before performing destructive operations. EOF diff --git a/Cargo.lock b/Cargo.lock index 0913c77..33c9816 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3319,7 +3319,7 @@ checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" [[package]] name = "rufust" -version = "1.1.0" +version = "1.2.0" dependencies = [ "ashpd", "embed-resource", @@ -3338,7 +3338,7 @@ dependencies = [ [[package]] name = "rufust-boot" -version = "1.1.0" +version = "1.2.0" dependencies = [ "rufust-core", "thiserror 2.0.19", @@ -3346,14 +3346,14 @@ dependencies = [ [[package]] name = "rufust-core" -version = "1.1.0" +version = "1.2.0" dependencies = [ "serde", ] [[package]] name = "rufust-downloads" -version = "1.1.0" +version = "1.2.0" dependencies = [ "serde", "serde_json", @@ -3363,7 +3363,7 @@ dependencies = [ [[package]] name = "rufust-helper" -version = "1.1.0" +version = "1.2.0" dependencies = [ "bzip2", "flate2", @@ -3383,7 +3383,7 @@ dependencies = [ [[package]] name = "rufust-helper-protocol" -version = "1.1.0" +version = "1.2.0" dependencies = [ "rufust-core", "serde", @@ -3393,11 +3393,11 @@ dependencies = [ [[package]] name = "rufust-i18n" -version = "1.1.0" +version = "1.2.0" [[package]] name = "rufust-image" -version = "1.1.0" +version = "1.2.0" dependencies = [ "libc", "md-5", @@ -3409,7 +3409,7 @@ dependencies = [ [[package]] name = "rufust-platform" -version = "1.1.0" +version = "1.2.0" dependencies = [ "rufust-core", "windows-sys 0.59.0", diff --git a/Cargo.toml b/Cargo.toml index 6be4d97..f79ba92 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ default-members = [ resolver = "2" [workspace.package] -version = "1.1.0" +version = "1.2.0" edition = "2021" rust-version = "1.85" license = "GPL-3.0-or-later" diff --git a/README.md b/README.md index 337aece..30705a9 100644 --- a/README.md +++ b/README.md @@ -141,7 +141,7 @@ The window runs with your normal rights. When you confirm an operation, Windows asks once for administrator approval, and a separate elevated copy of `rufust.exe` does the disk work; declining writes nothing. The executable is not code-signed yet, so SmartScreen may ask you to confirm the first launch. -Windows builds are published from the first release after 1.1.0. +Windows builds are published from 1.2.0 on. `SHA256SUMS` detects download corruption. GitHub build provenance attached to the release provides a separate publisher-verification path. diff --git a/apps/rufust/ui/appwindow.slint b/apps/rufust/ui/appwindow.slint index 6eb6fd2..5e9ef03 100644 --- a/apps/rufust/ui/appwindow.slint +++ b/apps/rufust/ui/appwindow.slint @@ -93,7 +93,7 @@ export component AppWindow inherits Window { in-out property show-about: false; in-out property show-advanced: false; in-out property capability-hint: ""; - in-out property app-version: "1.1.0"; + in-out property app-version: "1.2.0"; in property privilege-note: "Destructive writes use a polkit-authorized helper. The desktop process never holds ambient root for raw disks."; // —— Callbacks —— diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 29b7a31..a4ba4a2 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -131,7 +131,7 @@ workflow, then stage and verify it with: ```sh packaging/appimage/stage-appdir.sh target/release/rufust Rufust.AppDir appimagetool --runtime-file runtime-x86_64 Rufust.AppDir rufust.AppImage -packaging/appimage/verify-appimage.sh rufust.AppImage 1.1.0 2.28 +packaging/appimage/verify-appimage.sh rufust.AppImage 1.2.0 2.28 ``` The release workflow supplies SHA-verified appimagetool and type-2 runtime @@ -172,7 +172,7 @@ again. To build the installer yourself after the release build: ```powershell $icon = (Get-ChildItem target\release\build\rufust-*\out\rufust.ico)[0].FullName -& "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe" /DVersion=1.1.0 "/DIconFile=$icon" packaging\windows\rufust.iss +& "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe" /DVersion=1.2.0 "/DIconFile=$icon" packaging\windows\rufust.iss ``` The installer lands in `dist\`. diff --git a/docs/CAPABILITIES.md b/docs/CAPABILITIES.md index 80d639c..2a21fdd 100644 --- a/docs/CAPABILITIES.md +++ b/docs/CAPABILITIES.md @@ -70,7 +70,7 @@ Blocked only on Windows: ext2/3/4 creation (no Windows formatter) and ReFS creation (only Pro for Workstations, Enterprise, and Server editions allow it, through VDS). -## Unreleased: Windows support +## Changes in 1.2.0 Rufust now runs on Windows 10 and 11 (x64), alongside the Linux build, with the capabilities in the [Windows](#windows) table. The window stays diff --git a/docs/PROJECT_CONTEXT.md b/docs/PROJECT_CONTEXT.md index cd7a200..fe579c9 100644 --- a/docs/PROJECT_CONTEXT.md +++ b/docs/PROJECT_CONTEXT.md @@ -18,12 +18,13 @@ Debian/Ubuntu, Fedora, and Windows 10/11 (x64). Feature parity means implementing an upstream concept safely on each platform; it does not mean exposing a control before its full operation is implemented and verified. -## Current baseline: 1.1.0 +## Current baseline: 1.2.0 -Version 1.1.0 is the continuation baseline. Its public installers belong in the -[v1.1.0 release](https://github.com/NitroDiesel/rufust/releases/tag/v1.1.0). -The project was named Rufus Linux (`rufus-linux`) up to 1.0.1; 1.1.0 renamed it -to Rufust everywhere. Its packages replace `rufus-linux`, and the desktop app +Version 1.2.0 is the continuation baseline. Its public installers belong in the +[v1.2.0 release](https://github.com/NitroDiesel/rufust/releases/tag/v1.2.0). +1.2.0 is the first release with Windows support (below). The project was +named Rufus Linux (`rufus-linux`) up to 1.0.1; 1.1.0 renamed it to Rufust +everywhere. Its packages replace `rufus-linux`, and the desktop app still reads preferences from `~/.config/rufus-linux` until it saves its own. Release titles are `v`. [`PARITY.md`](PARITY.md) tracks every upstream Rufus feature and the order in which the rest will land. @@ -79,7 +80,7 @@ end-to-end implementation and its fixtures, integration tests, and boot tests exist. Supported standalone 512-byte-sector VHD/VHDX images convert when `qemu-nbd`, `nbdinfo`, and `nbdcopy` are installed. -## Windows support (unreleased, after 1.1.0) +## Windows support (since 1.2.0) Rufust also runs on Windows 10 and 11 (x64). The UI, planner, helper protocol, image analysis, Windows-media layout, answer files, and boot records @@ -109,8 +110,7 @@ renders the workbench in the fixed 560x720 window. CI runs these on `windows-2022`, and the release workflow adds `rufust--windows-x86_64-setup.exe` (Inno Setup, verified by a silent install and uninstall) and the portable `rufust--windows-x86_64.zip`. -No release containing Windows support -has been published yet; the next version bump publishes the first one. +The v1.2.0 release is the first to include them. ## Architecture map @@ -316,10 +316,9 @@ included in 0.1.3. These are known follow-ups, not claims that the current release is broken: -- Windows: smoke-test the zip on disposable physical USB media (flash drive - and USB SSD), boot-test Windows-built media, Authenticode-sign the - executable, and publish the first release that includes it. See - `WINDOWS.md`. +- Windows: smoke-test on disposable physical USB media (flash drive and USB + SSD), boot-test Windows-built media, and Authenticode-sign the executable + and installer. See `WINDOWS.md`. - Run a packaged, real-polkit smoke test on disposable physical USB media for formatting, raw writing, Windows media, verification, cancellation, and disconnect during write. Automated tests, loop-backed udisks2 tests, and diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILD index 11b24d0..d97241b 100644 --- a/packaging/arch/PKGBUILD +++ b/packaging/arch/PKGBUILD @@ -1,6 +1,6 @@ # Maintainer: Rufust contributors pkgname=rufust -pkgver=1.1.0 +pkgver=1.2.0 pkgrel=1 pkgdesc="Format and create bootable USB drives (Linux port inspired by Rufus)" arch=('x86_64' 'aarch64') diff --git a/packaging/debian/changelog b/packaging/debian/changelog index a66b4e4..d90af2d 100644 --- a/packaging/debian/changelog +++ b/packaging/debian/changelog @@ -1,3 +1,9 @@ +rufust (1.2.0-1) unstable; urgency=medium + + * Add Windows 10 and 11 support with an installer and a portable build. + + -- Rufust contributors Wed, 11 Nov 2026 00:00:00 +0800 + rufust (1.1.0-1) unstable; urgency=medium * Rename the project from Rufus Linux to Rufust; replace the rufus-linux package. diff --git a/packaging/metainfo/io.github.nitrodiesel.rufust.metainfo.xml b/packaging/metainfo/io.github.nitrodiesel.rufust.metainfo.xml index f0894a4..1237230 100644 --- a/packaging/metainfo/io.github.nitrodiesel.rufust.metainfo.xml +++ b/packaging/metainfo/io.github.nitrodiesel.rufust.metainfo.xml @@ -26,6 +26,12 @@ + + +

Rufust now also runs on Windows 10 and 11, with an installer and a + portable download. The Linux version is unchanged.

+
+

Rufus Linux is now called Rufust. Its packages replace the old diff --git a/packaging/rpm/rufust.spec b/packaging/rpm/rufust.spec index 71d0188..9a8787a 100644 --- a/packaging/rpm/rufust.spec +++ b/packaging/rpm/rufust.spec @@ -1,5 +1,5 @@ Name: rufust -Version: 1.1.0 +Version: 1.2.0 Release: 1%{?dist} Summary: Format and create bootable USB drives License: GPL-3.0-or-later @@ -57,6 +57,9 @@ done %{_datadir}/icons/hicolor/*/apps/io.github.nitrodiesel.rufust.png %changelog +* Wed Nov 11 2026 Rufust contributors - 1.2.0-1 +- Add Windows 10 and 11 support with an installer and a portable build + * Mon Nov 09 2026 Rufust contributors - 1.1.0-1 - Rename the project from Rufus Linux to Rufust diff --git a/packaging/windows/rufust.iss b/packaging/windows/rufust.iss index f71db22..2ee8615 100644 --- a/packaging/windows/rufust.iss +++ b/packaging/windows/rufust.iss @@ -1,7 +1,7 @@ ; Inno Setup script for the Rufust Windows installer. ; ; Build from the repository root after `cargo build -p rufust --release`: -; iscc /DVersion=1.1.0 /DIconFile= packaging\windows\rufust.iss +; iscc /DVersion=1.2.0 /DIconFile= packaging\windows\rufust.iss ; ; The installer writes to Program Files, so only administrators can replace ; the executable that the elevated disk worker runs. The app itself keeps its