From 69d5257645ed93ffacfa4bf2e0ccb2c19c80ccd1 Mon Sep 17 00:00:00 2001 From: "Frank Chiarulli Jr." Date: Mon, 16 Nov 2026 23:41:12 -0400 Subject: [PATCH 01/10] Give the dongle's WinUSB interface a device interface GUID The firmware asked Windows for WinUSB through its MS OS 2.0 descriptors but never supplied DeviceInterfaceGUIDs, so Windows didn't expose the vendor interface of the composite device to apps and every dongle command failed with "Could not find DeviceInterfaceGUIDs in registry". Advertise a fixed GUID (shared through restorekit-dongle-proto) and pin the vendor interface number the host relies on. --- crates/dongle-lite-fw/Cargo.lock | 2 +- crates/dongle-lite-fw/README.md | 5 ++++- crates/dongle-lite-fw/src/main.rs | 10 +++++++++- crates/restorekit-dongle-proto/src/lib.rs | 9 +++++++++ 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/dongle-lite-fw/Cargo.lock b/crates/dongle-lite-fw/Cargo.lock index 8d0b1d0..d42ef1a 100644 --- a/crates/dongle-lite-fw/Cargo.lock +++ b/crates/dongle-lite-fw/Cargo.lock @@ -1268,7 +1268,7 @@ checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" [[package]] name = "restorekit-dongle-proto" -version = "0.6.0" +version = "0.6.2" [[package]] name = "rgb" diff --git a/crates/dongle-lite-fw/README.md b/crates/dongle-lite-fw/README.md index 4bea6b5..facec11 100644 --- a/crates/dongle-lite-fw/README.md +++ b/crates/dongle-lite-fw/README.md @@ -209,7 +209,10 @@ cables are actually USB 2 and won't carry SBU) before moving to M1 schematic. Besides the human CDC console, the firmware exposes a **vendor-specific USB interface** (`bInterfaceClass = 0xFF`) that the `restorekit` SDK drives over `nusb` control transfers — no serial port, no OS driver, works the same on -macOS/Linux/Windows (Windows needs the interface bound to WinUSB). The device +macOS/Linux/Windows. On Windows the MS OS 2.0 descriptors bind WinUSB and give +the interface its device interface GUID (`WINUSB_INTERFACE_GUID` in +`restorekit-dongle-proto`); firmware through 0.1.3 left the GUID out, so Windows +never exposed the interface, and `restorekit setup-driver` adds it for those. The device also enumerates with a **unique USB serial** derived from the RP2350 chip ID (e.g. `DL-1A2B3C4D`), so multiple dongles are individually addressable. diff --git a/crates/dongle-lite-fw/src/main.rs b/crates/dongle-lite-fw/src/main.rs index d4e52c3..87cd057 100644 --- a/crates/dongle-lite-fw/src/main.rs +++ b/crates/dongle-lite-fw/src/main.rs @@ -492,10 +492,18 @@ async fn main(_spawner: Spawner) { static VHANDLER: StaticCell = StaticCell::new(); let vendor_iface = { let mut func = builder.function(0xFF, 0x00, 0x00); - // Tell Windows this function speaks WinUSB. + // Tell Windows this function speaks WinUSB, and give it an interface + // GUID: without one Windows never exposes the interface of a composite + // device to apps, so the SDK can't open it. func.msos_feature(msos::CompatibleIdFeatureDescriptor::new("WINUSB", "")); + func.msos_feature(msos::RegistryPropertyFeatureDescriptor::new( + "DeviceInterfaceGUIDs", + msos::PropertyData::RegMultiSz(&[proto::WINUSB_INTERFACE_GUID]), + )); let mut iface = func.interface(); let n = iface.interface_number(); + // The host's Windows driver setup binds this interface by number. + assert_eq!(u8::from(n), proto::VENDOR_IFACE); let _alt = iface.alt_setting(0xFF, 0x00, 0x00, None); n }; diff --git a/crates/restorekit-dongle-proto/src/lib.rs b/crates/restorekit-dongle-proto/src/lib.rs index 6fd9beb..0e43a10 100644 --- a/crates/restorekit-dongle-proto/src/lib.rs +++ b/crates/restorekit-dongle-proto/src/lib.rs @@ -44,6 +44,15 @@ pub const SERIAL_PREFIX_PRO: &str = "DP-"; /// Class of the vendor-specific interface the SDK drives. pub const VENDOR_CLASS: u8 = 0xFF; +/// Interface number of the vendor interface (after the two CDC ACM functions). +pub const VENDOR_IFACE: u8 = 4; + +/// WinUSB device interface GUID for the vendor interface. Windows only exposes a +/// WinUSB interface of a composite device to apps (nusb, libusb) when it has one, +/// so the firmware hands it out in its MS OS 2.0 descriptors and the host's +/// driver setup writes it for dongles whose firmware predates that. +pub const WINUSB_INTERFACE_GUID: &str = "{82A7EB70-6C66-43B6-BDCB-D957FCC49307}"; + // bRequest values on the vendor interface (vendor type, interface recipient). /// Control OUT: execute a command; wValue = `VCMD_*`. pub const VREQ_CMD: u8 = 0x01; From 079e28b663de73c82445fea1f7fddd2b38af960c Mon Sep 17 00:00:00 2001 From: "Frank Chiarulli Jr." Date: Mon, 16 Nov 2026 23:41:12 -0400 Subject: [PATCH 02/10] Make setup-driver work with Apple's drivers and dongles on Windows - Force our WinUSB onto present targets like the restore-mode watcher does. Windows Update installs Apple's WHQL applekis.inf for a KIS Mac, which outranks our package, so pnputil /install left it bound and restorekit couldn't read the Mac. - Bind the dongle's vendor interface with its interface GUID, for firmware that doesn't supply it, and run with only a dongle connected. - Trust the signing cert through X509Store: Import-Certificate into LocalMachine\TrustedPublisher is refused on current Windows 11. - Fail when pnputil can't stage the package and include its output. - Point dongle open failures and unreadable KIS Macs at setup-driver. --- crates/restorekit/src/dongle.rs | 10 +- crates/restorekit/src/driver.rs | 282 ++++++++++++++++++++++++++------ crates/restorekit/src/error.rs | 9 +- 3 files changed, 249 insertions(+), 52 deletions(-) diff --git a/crates/restorekit/src/dongle.rs b/crates/restorekit/src/dongle.rs index 44f990c..955cd3a 100644 --- a/crates/restorekit/src/dongle.rs +++ b/crates/restorekit/src/dongle.rs @@ -508,7 +508,15 @@ impl Dongle { let iface = dev .claim_interface(self.vendor_iface) .wait() - .map_err(Error::from)?; + .map_err(|e| { + // On Windows the interface can't be opened until WinUSB is + // bound with an interface GUID, which `setup-driver` does. + if cfg!(target_os = "windows") && e.kind() == nusb::ErrorKind::Unsupported { + Error::UsbPermission(e.to_string()) + } else { + Error::from(e) + } + })?; Ok(DongleHandle { iface, iface_num: self.vendor_iface, diff --git a/crates/restorekit/src/driver.rs b/crates/restorekit/src/driver.rs index f7835ff..1005e8d 100644 --- a/crates/restorekit/src/driver.rs +++ b/crates/restorekit/src/driver.rs @@ -18,6 +18,8 @@ use std::io::Write; use std::process::Command; +use restorekit_dongle_proto as proto; + use crate::error::{Error, Result}; use crate::progress::{Event, ProgressFn}; @@ -61,6 +63,42 @@ pub struct Target { /// Enumerate connected Apple devices in DFU, recovery, or restore mode. pub fn connected_targets() -> Result> { + Ok(present_instance_ids()? + .iter() + .filter_map(|id| target_pid_from_instance_id(id)) + .map(|pid| Target { + pid, + name: format!("Apple device (mode {pid:#06x})"), + }) + .collect()) +} + +/// How many RecoverKit dongles are connected (by their vendor interface). +fn connected_dongles() -> Result { + Ok(present_instance_ids()? + .iter() + .filter(|id| is_dongle_interface(id)) + .count()) +} + +/// The PnP hardware id of a dongle's vendor interface. +fn dongle_interface_hwid() -> String { + format!( + "USB\\VID_{:04X}&PID_{:04X}&MI_{:02X}", + proto::VID, + proto::PID, + proto::VENDOR_IFACE + ) +} + +fn is_dongle_interface(instance_id: &str) -> bool { + instance_id + .to_ascii_uppercase() + .starts_with(&format!("{}\\", dongle_interface_hwid())) +} + +/// Instance ids of every present device. +fn present_instance_ids() -> Result> { use windows_sys::Win32::Devices::DeviceAndDriverInstallation::{ SetupDiDestroyDeviceInfoList, SetupDiEnumDeviceInfo, SetupDiGetClassDevsW, SetupDiGetDeviceInstanceIdW, DIGCF_ALLCLASSES, DIGCF_PRESENT, SP_DEVINFO_DATA, @@ -80,7 +118,7 @@ pub fn connected_targets() -> Result> { )); } - let mut targets = Vec::new(); + let mut ids = Vec::new(); let mut index = 0; loop { let mut info = SP_DEVINFO_DATA { @@ -108,16 +146,10 @@ pub fn connected_targets() -> Result> { .iter() .position(|&c| c == 0) .unwrap_or(required as usize); - let instance_id = String::from_utf16_lossy(&instance_id[..len]); - if let Some(pid) = target_pid_from_instance_id(&instance_id) { - targets.push(Target { - pid, - name: format!("Apple device (mode {pid:#06x})"), - }); - } + ids.push(String::from_utf16_lossy(&instance_id[..len])); } SetupDiDestroyDeviceInfoList(devices); - Ok(targets) + Ok(ids) } } @@ -129,22 +161,41 @@ fn target_pid_from_instance_id(instance_id: &str) -> Option { is_target_pid(pid).then_some(pid) } -/// Bind the WinUSB driver to every connected Apple DFU/recovery/restore device, -/// so libusb can open it. Returns the number of devices set up. +/// Bind the WinUSB driver to every connected Apple DFU/recovery/restore device +/// and RecoverKit dongle, so libusb and nusb can open them. Returns the number +/// of devices set up. /// /// Must run elevated (the CLI handles that). pub fn install_winusb(progress: ProgressFn) -> Result { let targets = connected_targets()?; - if targets.is_empty() { + let dongles = connected_dongles()?; + if targets.is_empty() && dongles == 0 { return Err(Error::DriverInstall( - "no Apple device in DFU or recovery mode is connected — put the target into DFU \ - (see `restorekit status`) and re-run" + "no Apple device in DFU or recovery mode and no RecoverKit dongle is connected — \ + plug in the dongle or put the target into DFU (see `restorekit status`) and re-run" .into(), )); } progress(Event::DriverSetupStarting); + run_setup_script(false)?; + + for t in &targets { + progress(Event::DriverBound { + name: t.name.clone(), + }); + } + for _ in 0..dongles { + progress(Event::DriverBound { + name: "RecoverKit dongle".into(), + }); + } + Ok(targets.len() + dongles) +} +/// Sign and stage our WinUSB package, then (unless `stage_only`) force it onto +/// every connected device it covers. Must run elevated. +fn run_setup_script(stage_only: bool) -> Result<()> { // A private work dir holding only the INF(s) — the catalog hashes this // directory, so nothing else may live in it. The script goes alongside. let base = std::env::temp_dir(); @@ -163,12 +214,18 @@ pub fn install_winusb(progress: ProgressFn) -> Result { // CREATE_NO_WINDOW: don't flash a PowerShell console (matters for the GUI). use std::os::windows::process::CommandExt; const CREATE_NO_WINDOW: u32 = 0x0800_0000; - let output = Command::new("powershell") - .creation_flags(CREATE_NO_WINDOW) + let mut cmd = Command::new("powershell"); + cmd.creation_flags(CREATE_NO_WINDOW) .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"]) .arg(&script) .arg("-WorkDir") .arg(&work) + .arg("-DeviceRegex") + .arg(bind_regex()); + if stage_only { + cmd.arg("-StageOnly"); + } + let output = cmd .output() .map_err(|e| Error::DriverInstall(format!("failed to run PowerShell: {e}"))); @@ -177,21 +234,29 @@ pub fn install_winusb(progress: ProgressFn) -> Result { let output = output?; if !output.status.success() { - let mut detail = String::from_utf8_lossy(&output.stderr).trim().to_string(); - if detail.is_empty() { - detail = String::from_utf8_lossy(&output.stdout).trim().to_string(); - } + // pnputil's own output (on stdout) usually says why; keep both. + let detail = [&output.stderr, &output.stdout] + .iter() + .map(|b| String::from_utf8_lossy(b).trim().to_string()) + .filter(|s| !s.is_empty()) + .collect::>() + .join("\n"); return Err(Error::DriverInstall(format!( "WinUSB setup did not complete: {detail}" ))); } + Ok(()) +} - for t in &targets { - progress(Event::DriverBound { - name: t.name.clone(), - }); - } - Ok(targets.len()) +/// PowerShell regex matching the instance ids the setup script binds: the +/// Apple modes in [`DRIVER_PIDS`] and the dongle's vendor interface. +fn bind_regex() -> String { + let pids: Vec = DRIVER_PIDS.iter().map(|p| format!("{p:04X}")).collect(); + format!( + "^USB\\\\VID_{APPLE_VID:04X}&PID_({})\\\\|^{}\\\\", + pids.join("|"), + dongle_interface_hwid().replace('\\', "\\\\") + ) } /// A WinUSB device INF binding the inbox `winusb.sys` to every Apple product id @@ -227,6 +292,14 @@ fn winusb_inf(pids: &[u16]) -> String { "%DeviceName% = WINUSB_RESTORE_Install, USB\\VID_{APPLE_VID:04X}&PID_{pid:04X}&RESTORE_MODE&MI_00\n" )); } + // The dongle's vendor interface. Its firmware asks Windows for WinUSB but, + // through 0.1.3, gave no interface GUID, without which Windows never exposes + // that interface to apps; binding it here supplies the GUID. More specific + // than the generic WinUSB compatible-id match, so it wins that ranking. + models.push_str(&format!( + "%DongleName% = WINUSB_DONGLE_Install, {}\n", + dongle_interface_hwid() + )); format!( r#"; Generated by RestoreKit - binds WinUSB to an Apple device so libusb can access it. [Version] @@ -235,7 +308,7 @@ Class = USBDevice ClassGuid = {{88BAE032-5A81-49f0-BC3D-A4FF138216D6}} Provider = %ProviderName% CatalogFile = restorekit_winusb.cat -DriverVer = 01/01/2024,1.0.0.1 +DriverVer = 01/01/2024,1.0.0.2 [Manufacturer] %ProviderName% = Standard,NTamd64,NTarm64 @@ -314,19 +387,45 @@ AddReg = WINUSB_RESTORE_AddReg [WINUSB_RESTORE_AddReg] HKR,,DeviceInterfaceGUIDs,0x10000,"{{3F966BD9-FA04-4EC5-991C-D326973B5128}}" +[WINUSB_DONGLE_Install.NT] +Include = winusb.inf +Needs = WINUSB.NT + +[WINUSB_DONGLE_Install.NT.Services] +Include = winusb.inf +Needs = WINUSB.NT.Services + +[WINUSB_DONGLE_Install.NT.HW] +AddReg = WINUSB_DONGLE_AddReg + +[WINUSB_DONGLE_AddReg] +HKR,,DeviceInterfaceGUIDs,0x10000,"{dongle_guid}" + [Strings] ProviderName = "RestoreKit" DeviceName = "Apple Mobile Device (RestoreKit WinUSB)" -"# +DongleName = "RecoverKit Dongle (RestoreKit WinUSB)" +"#, + dongle_guid = proto::WINUSB_INTERFACE_GUID ) } /// PowerShell that signs and installs the WinUSB package for `$WorkDir`. /// /// Reuses a stable `CN=RestoreKit WinUSB` code-signing cert (creating it once), -/// builds + signs a catalog over the INF(s), trusts the cert, binds the driver, -/// then verifies WinUSB actually attached — exiting non-zero if not. -const WINUSB_SETUP_PS1: &str = r#"param([Parameter(Mandatory=$true)][string]$WorkDir) +/// builds + signs a catalog over the INF(s), trusts the cert and stages the +/// package. Unless `-StageOnly`, it then forces the package onto every present +/// device matching `-DeviceRegex` and verifies WinUSB attached, exiting +/// non-zero if not. +/// +/// Forcing is needed because Windows Update installs Apple's own WHQL-signed +/// drivers (e.g. `applekis.inf` for 05ac:1881), which outrank our self-signed +/// package, so a plain `pnputil /install` leaves them in place. +const WINUSB_SETUP_PS1: &str = r#"param( + [Parameter(Mandatory=$true)][string]$WorkDir, + [string]$DeviceRegex = '^$', + [switch]$StageOnly +) $ErrorActionPreference = 'Stop' $cat = Join-Path $WorkDir 'restorekit_winusb.cat' $subject = 'CN=RestoreKit WinUSB' @@ -339,18 +438,58 @@ if (-not $cert) { } New-FileCatalog -Path $WorkDir -CatalogFilePath $cat -CatalogVersion 2 | Out-Null Set-AuthenticodeSignature -FilePath $cat -Certificate $cert | Out-Null -$cer = Join-Path $WorkDir 'restorekit.cer' -Export-Certificate -Cert $cert -FilePath $cer | Out-Null -Import-Certificate -FilePath $cer -CertStoreLocation Cert:\LocalMachine\Root | Out-Null -Import-Certificate -FilePath $cer -CertStoreLocation Cert:\LocalMachine\TrustedPublisher | Out-Null -Get-ChildItem $WorkDir -Filter '*.inf' | ForEach-Object { - pnputil /add-driver $_.FullName /install | Out-Host +# Trust the cert machine-wide through X509Store: current Windows 11 refuses +# Import-Certificate into LocalMachine\TrustedPublisher, even elevated. +$pub = [Security.Cryptography.X509Certificates.X509Certificate2]::new($cert.RawData) +foreach ($name in 'Root', 'TrustedPublisher') { + $store = [Security.Cryptography.X509Certificates.X509Store]::new($name, 'LocalMachine') + $store.Open('ReadWrite') + $store.Add($pub) + $store.Close() +} +$infFile = Get-ChildItem $WorkDir -Filter '*.inf' | Select-Object -First 1 +$log = pnputil /add-driver $infFile.FullName /install | Out-String +Write-Output $log +if ($log -match 'Failed to add driver package') { + Write-Error "pnputil could not stage the driver package" + exit 1 +} +# The staged copy (oemNN.inf) pnputil just published. +$leaf = if ($log -match 'Published Name:\s+(oem\d+\.inf)') { $Matches[1] } else { $null } +if (-not $leaf) { + Write-Error 'pnputil did not report a published driver package' + exit 1 +} +if ($StageOnly) { exit 0 } + +Add-Type @" +using System; +using System.Runtime.InteropServices; +public static class RkNewDev { + [DllImport("newdev.dll", CharSet=CharSet.Unicode, SetLastError=true)] + public static extern bool UpdateDriverForPlugAndPlayDevices( + IntPtr hwnd, string HardwareId, string FullInfPath, uint InstallFlags, out bool bReboot); +} +"@ +$staged = Join-Path $env:windir "INF\$leaf" +$devices = Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | + Where-Object { $_.InstanceId -match $DeviceRegex } +foreach ($dev in $devices) { + $infNow = (Get-PnpDeviceProperty -InstanceId $dev.InstanceId -KeyName DEVPKEY_Device_DriverInfPath -ErrorAction SilentlyContinue).Data + if ($infNow -eq $leaf) { continue } + # INSTALLFLAG_FORCE (0x1) | INSTALLFLAG_NONINTERACTIVE (0x4). + $hwid = $dev.InstanceId -replace '\\[^\\]+$', '' + $reboot = $false + if (-not [RkNewDev]::UpdateDriverForPlugAndPlayDevices([IntPtr]::Zero, $hwid, $staged, 0x5, [ref]$reboot)) { + $code = [Runtime.InteropServices.Marshal]::GetLastWin32Error() + Write-Output ("could not bind {0} (was {1}): error 0x{2:X8}" -f $dev.InstanceId, $infNow, $code) + } } $svcs = Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | - Where-Object { $_.InstanceId -match 'VID_05AC' } | + Where-Object { $_.InstanceId -match $DeviceRegex } | ForEach-Object { (Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName 'DEVPKEY_Device_Service' -ErrorAction SilentlyContinue).Data } if ($svcs -contains 'WINUSB' -or $svcs -contains 'winusb') { exit 0 } -Write-Error 'WinUSB was not bound to any connected Apple device' +Write-Error 'WinUSB was not bound to any connected device' exit 1 "#; @@ -461,14 +600,30 @@ fn is_elevated() -> bool { } } +/// Where the restore-mode watcher logs what it did, for diagnosing a restore +/// that stalls at "waiting for device to enter restore mode". +pub fn restore_watch_log() -> std::path::PathBuf { + std::env::temp_dir().join("restorekit-restore-watch.log") +} + /// The elevated watcher worker, invoked when this binary is rerun with -/// [`RESTORE_WATCH_ARG`]. Runs the PowerShell force-bind helper as a child -/// (inheriting this process's elevation) and returns when it exits — i.e. when -/// the restore removes the liveness file or the device leaves after being bound. +/// [`RESTORE_WATCH_ARG`]. Stages our WinUSB package (a restore can reach this +/// point without `setup-driver` ever having run: with Apple's own driver +/// installed, DFU and recovery work without it), then runs the PowerShell +/// force-bind helper as a child (inheriting this process's elevation) and +/// returns when it exits — i.e. when the restore removes the liveness file or +/// the device leaves after being bound. pub fn run_restore_mode_watch_worker(liveness: &std::path::Path) { use std::os::windows::process::CommandExt; const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let log = restore_watch_log(); + let staged = match run_setup_script(true) { + Ok(()) => "staged the WinUSB package".to_string(), + Err(e) => format!("staging the WinUSB package failed: {e}"), + }; + let _ = std::fs::write(&log, format!("{staged}\r\n")); + let script = std::env::temp_dir().join(format!( "restorekit-restore-watch-{}.ps1", std::process::id() @@ -482,6 +637,8 @@ pub fn run_restore_mode_watch_worker(liveness: &std::path::Path) { .arg(&script) .arg("-LivenessFile") .arg(liveness) + .arg("-LogFile") + .arg(&log) .status(); let _ = std::fs::remove_file(&script); } @@ -524,8 +681,13 @@ fn launch_elevated_hidden(exe: &str, params: &str) -> Result<()> { /// device and force our WinUSB onto it (keeping `appleusb.inf` in the store). /// Exits when the restore signals completion (liveness file gone), when the /// device leaves after being bound, or after a safety deadline. -const RESTORE_WATCH_PS1: &str = r#"param([string]$LivenessFile) +const RESTORE_WATCH_PS1: &str = r#"param([string]$LivenessFile, [string]$LogFile) $ErrorActionPreference = 'SilentlyContinue' +$script:last = '' +function Log($msg) { + if ($LogFile -and $msg -ne $script:last) { Add-Content -Path $LogFile -Value ("{0:HH:mm:ss} {1}" -f (Get-Date), $msg) } + $script:last = $msg +} Add-Type @" using System; using System.Runtime.InteropServices; @@ -538,17 +700,18 @@ public static class RkNewDev { # INSTALLFLAG_FORCE (0x1): install even though Apple's WHQL driver outranks ours. # INSTALLFLAG_NONINTERACTIVE (0x4): never prompt. $FLAGS = 0x1 -bor 0x4 -# Our staged WinUSB package (has the RESTORE_MODE interface entries). -$inf = (Get-ChildItem C:\Windows\INF\oem*.inf -ErrorAction SilentlyContinue | Where-Object { +# Our newest staged WinUSB package (has the RESTORE_MODE interface entries). +$inf = (Get-ChildItem (Join-Path $env:windir 'INF\oem*.inf') -ErrorAction SilentlyContinue | Where-Object { $c = Get-Content $_.FullName -Raw -ErrorAction SilentlyContinue $c -match 'RestoreKit' -and $c -match 'RESTORE_MODE' -} | Select-Object -First 1).FullName -if (-not $inf) { exit 1 } +} | Sort-Object LastWriteTime -Descending | Select-Object -First 1).FullName +if (-not $inf) { Log 'no staged RestoreKit WinUSB package found'; exit 1 } +Log "using $inf" $leaf = Split-Path $inf -Leaf $deadline = (Get-Date).AddMinutes(45) $bound = $false while ((Get-Date) -lt $deadline) { - if ($LivenessFile -and -not (Test-Path $LivenessFile)) { break } + if ($LivenessFile -and -not (Test-Path $LivenessFile)) { Log 'restore ended'; break } $dev = Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | Where-Object { $_.InstanceId -match 'VID_05AC&PID_12[0-9A-Fa-f]{2}&RESTORE_MODE&MI_00' } | Select-Object -First 1 @@ -557,10 +720,13 @@ while ((Get-Date) -lt $deadline) { if ($infNow -ne $leaf) { $hwid = ($dev.InstanceId -replace '\\[^\\]+$', '') $reboot = $false - [RkNewDev]::UpdateDriverForPlugAndPlayDevices([IntPtr]::Zero, $hwid, $inf, $FLAGS, [ref]$reboot) | Out-Null + $ok = [RkNewDev]::UpdateDriverForPlugAndPlayDevices([IntPtr]::Zero, $hwid, $inf, $FLAGS, [ref]$reboot) + $code = [Runtime.InteropServices.Marshal]::GetLastWin32Error() + Log ("{0} was on {1}; bind -> ok={2} error=0x{3:X8}" -f $dev.InstanceId, $infNow, $ok, $code) } $bound = $true } elseif ($bound) { + Log 'restore-mode device left' break } Start-Sleep -Milliseconds 350 @@ -598,5 +764,23 @@ mod tests { assert!(inf.contains("{ED82A167-D61A-4AF6-9AB6-11E52236C576}")); assert!(inf.contains("{AF633FF1-1170-4CA6-AE9E-08D001421EAA}")); assert!(inf.contains("{B36F4137-F4EF-4BFC-A25A-C2410768EE37}")); + assert!(inf.contains("USB\\VID_16D0&PID_14F0&MI_04\n")); + assert!(inf.contains(proto::WINUSB_INTERFACE_GUID)); + } + + #[test] + fn dongle_interface_is_recognized() { + assert!(is_dongle_interface("USB\\VID_16D0&PID_14F0&MI_04\\6&2E2718E1&0&0004")); + assert!(!is_dongle_interface("USB\\VID_16D0&PID_14F0&MI_00\\6&2E2718E1&0&0000")); + assert!(!is_dongle_interface("USB\\VID_16D0&PID_14F0\\DL-6BAF14C4")); + } + + #[test] + fn bind_regex_is_a_powershell_regex_over_instance_ids() { + assert_eq!( + bind_regex(), + "^USB\\\\VID_05AC&PID_(1222|1227|1280|1281|1282|1283|F014|1881)\\\\\ + |^USB\\\\VID_16D0&PID_14F0&MI_04\\\\" + ); } } diff --git a/crates/restorekit/src/error.rs b/crates/restorekit/src/error.rs index 6615dd4..3eba888 100644 --- a/crates/restorekit/src/error.rs +++ b/crates/restorekit/src/error.rs @@ -125,7 +125,10 @@ fn kis_unreadable_message() -> &'static str { shows up, so retrying without re-entering DFU won't help" } else if cfg!(target_os = "windows") { "the Mac is in DFU over Apple's Debug USB interface (05ac:1881), but restorekit couldn't \ - read its identity. Run `restorekit setup-driver` so WinUSB is bound to it, then retry" + read its identity. Run `restorekit setup-driver` so WinUSB is bound to it, then put the \ + Mac back into DFU (`restorekit reboot`, then `restorekit dfu`) and retry. Windows Update \ + installs Apple's own driver for it, and once that driver has had the Mac it only works \ + again after re-entering DFU" } else { "the Mac is in DFU over Apple's Debug USB interface (05ac:1881), but restorekit couldn't \ read its identity. Check USB permissions (the udev rule covers 05ac:1881) and retry" @@ -159,7 +162,9 @@ on its own, so pass the full path: sudo {exe} ..." ) } else if cfg!(target_os = "windows") { - "Run `restorekit setup-driver` to bind the WinUSB driver to the cabled Mac.".into() + "Run `restorekit setup-driver` to bind the WinUSB driver to the cabled Mac and the \ + RecoverKit dongle." + .into() } else { format!("Re-run as root: sudo {exe} ...") } From f68a808d3c04a69f9278773094affc6b49497911 Mon Sep 17 00:00:00 2001 From: "Frank Chiarulli Jr." Date: Mon, 16 Nov 2026 23:41:12 -0400 Subject: [PATCH 03/10] Stage the WinUSB package in the restore-mode watcher With Apple's driver installed, DFU and recovery work without setup-driver, so a restore could reach restore mode with no RestoreKit package staged. The watcher then had nothing to bind, Apple's driver kept the interface, and the restore hung at "Waiting for device to enter restore mode" with libusb failing to open it (error 50). The elevated watcher now stages the package first and logs what it did, and the restore stops up front when the watcher can't start (UAC declined) instead of hanging later. Refs #56 --- crates/restorekit/src/restore.rs | 11 ++++++++++- docs/windows-restore.md | 28 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/crates/restorekit/src/restore.rs b/crates/restorekit/src/restore.rs index b7ff7d7..a2d7ba9 100644 --- a/crates/restorekit/src/restore.rs +++ b/crates/restorekit/src/restore.rs @@ -264,8 +264,17 @@ pub fn restore( // On Windows the Mac's restore-mode interface is claimed by Apple's driver, // which libusb can't open; spawn an elevated watcher (one UAC) that forces // our WinUSB onto it when it appears. Held for the duration of the restore. + // Without it the restore would run for minutes and then stall waiting for + // restore mode, so stop now instead. #[cfg(target_os = "windows")] - let _restore_watcher = crate::driver::spawn_restore_mode_watcher(); + let _restore_watcher = crate::driver::spawn_restore_mode_watcher().ok_or_else(|| { + Error::DriverInstall( + "couldn't start the restore-mode USB helper (was the Windows UAC prompt \ + declined?). Without it the restore stalls once the Mac enters restore mode; \ + retry and approve the prompt" + .into(), + ) + })?; let mut attempt = 1; loop { diff --git a/docs/windows-restore.md b/docs/windows-restore.md index 01822d3..4d39193 100644 --- a/docs/windows-restore.md +++ b/docs/windows-restore.md @@ -54,12 +54,40 @@ BaseSystem → recovered. The restore-mode phase needed three pieces: elevated watcher (one UAC, branded restorekit, skipped when already admin) that force-binds our WinUSB to the restore-mode device when it appears — per-restore, since Apple's driver reclaims it each time. `appleusb.inf` stays in the store. +- **The watcher stages the driver package itself.** With Apple's own driver + installed (iTunes, Apple Devices, or Windows Update), DFU and recovery work + without `setup-driver`, so a restore could reach restore mode with no + RestoreKit package in the store; the watcher then had nothing to bind and the + restore stalled at "waiting for device to enter restore mode" (#56). The + elevated watcher now stages the package before it starts watching, logs what + it did to `%TEMP%\restorekit-restore-watch.log`, and the restore stops up + front if the watcher can't start (UAC declined) instead of stalling later. +- **`setup-driver` forces WinUSB over Apple's drivers.** Windows Update + installs Apple's WHQL-signed `applekis.inf` for a KIS Mac (05ac:1881), which + outranks our self-signed package, so `pnputil /install` left it in place and + restorekit couldn't read the Mac. `setup-driver` now force-binds every present + target like the restore-mode watcher does. A KIS Mac that Apple's driver has + already opened only answers again after re-entering DFU. +- **Dongles work on Windows.** The dongle firmware asked for WinUSB but gave no + device interface GUID, so Windows never exposed the vendor interface to + nusb ("Could not find DeviceInterfaceGUIDs in registry"). The next firmware adds + it; `setup-driver` binds the interface with the GUID for older firmware, and + runs with only a dongle connected. +- **Certificate trust.** `Import-Certificate` into + `LocalMachine\TrustedPublisher` is refused on current Windows 11 even when + elevated; the setup script uses `X509Store` instead. - **Throughput confirmed.** With the 0ms-while-connected event loop, the CLI streams `Cryptex1,systemOS` at ~35 MB/s (near USB-2.0 line rate) — the embedded usbmuxd + WinUSB bulk path is not a bottleneck. ### Known issues +- **Windows on ARM.** Code Integrity rejects our self-signed catalog there + ("Driver package signer is not trusted by system, and Code Integrity is + enforced"), so `setup-driver` can't stage the package unless test signing is + on (`bcdedit /set testsigning on`). Everything else, including the x64 build + under emulation, works once it's staged. + - **Desktop app throughput.** The same restore that runs at ~35 MB/s from the CLI is much slower in the desktop app (the muxer gets fed at only tens of packets/sec). The C/USB stack is identical, so the throttle is somewhere in the From 453de2649aa1167f0bc582194112f82dc31bc9b1 Mon Sep 17 00:00:00 2001 From: "Frank Chiarulli Jr." Date: Tue, 17 Nov 2026 10:12:36 -0400 Subject: [PATCH 04/10] Format the dongle and driver changes --- crates/restorekit/src/dongle.rs | 21 +++++++++------------ crates/restorekit/src/driver.rs | 8 ++++++-- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/crates/restorekit/src/dongle.rs b/crates/restorekit/src/dongle.rs index 955cd3a..fbd22f8 100644 --- a/crates/restorekit/src/dongle.rs +++ b/crates/restorekit/src/dongle.rs @@ -505,18 +505,15 @@ impl Dongle { }) .ok_or(Error::NoDongle)?; let dev = info.open().wait().map_err(Error::from)?; - let iface = dev - .claim_interface(self.vendor_iface) - .wait() - .map_err(|e| { - // On Windows the interface can't be opened until WinUSB is - // bound with an interface GUID, which `setup-driver` does. - if cfg!(target_os = "windows") && e.kind() == nusb::ErrorKind::Unsupported { - Error::UsbPermission(e.to_string()) - } else { - Error::from(e) - } - })?; + let iface = dev.claim_interface(self.vendor_iface).wait().map_err(|e| { + // On Windows the interface can't be opened until WinUSB is + // bound with an interface GUID, which `setup-driver` does. + if cfg!(target_os = "windows") && e.kind() == nusb::ErrorKind::Unsupported { + Error::UsbPermission(e.to_string()) + } else { + Error::from(e) + } + })?; Ok(DongleHandle { iface, iface_num: self.vendor_iface, diff --git a/crates/restorekit/src/driver.rs b/crates/restorekit/src/driver.rs index 1005e8d..833a109 100644 --- a/crates/restorekit/src/driver.rs +++ b/crates/restorekit/src/driver.rs @@ -770,8 +770,12 @@ mod tests { #[test] fn dongle_interface_is_recognized() { - assert!(is_dongle_interface("USB\\VID_16D0&PID_14F0&MI_04\\6&2E2718E1&0&0004")); - assert!(!is_dongle_interface("USB\\VID_16D0&PID_14F0&MI_00\\6&2E2718E1&0&0000")); + assert!(is_dongle_interface( + "USB\\VID_16D0&PID_14F0&MI_04\\6&2E2718E1&0&0004" + )); + assert!(!is_dongle_interface( + "USB\\VID_16D0&PID_14F0&MI_00\\6&2E2718E1&0&0000" + )); assert!(!is_dongle_interface("USB\\VID_16D0&PID_14F0\\DL-6BAF14C4")); } From 7d6257389df7e9f5f6b418fcb868d0a1e56f034e Mon Sep 17 00:00:00 2001 From: "Frank Chiarulli Jr." Date: Tue, 17 Nov 2026 10:12:36 -0400 Subject: [PATCH 05/10] Use Apple's driver stack on Windows when it's installed Windows Update installs Apple's drivers for DFU, recovery and KIS, and libirecovery's Windows backend already talks to them. The two gaps were restore mode and our own KIS identify. - Restore mode: when Apple Mobile Device Service (iTunes, Apple Devices) is listening on 127.0.0.1:27015 it muxes the restore-mode interface through Apple's driver. Use it instead of starting the embedded usbmuxd (which would fail to bind that port) and the WinUSB watcher. - KIS identify: with AppleKIS bound, read the identity through the GET_INFO ioctl on its KIS child device, as libirecovery does, instead of WinUSB. - driver_ready counts Apple's DFU and KIS drivers as ready. With Apple's service installed, a full restore needs no RestoreKit driver package, UAC prompt or test signing, which also covers Windows on ARM. --- crates/restorekit-cli/src/commands/restore.rs | 11 +- crates/restorekit/Cargo.toml | 2 + crates/restorekit/src/device.rs | 10 +- crates/restorekit/src/kis.rs | 156 ++++++++++++++++++ crates/restorekit/src/restore.rs | 32 +++- crates/restorekit/src/usbmuxd.rs | 8 + docs/windows-restore.md | 17 +- 7 files changed, 218 insertions(+), 18 deletions(-) diff --git a/crates/restorekit-cli/src/commands/restore.rs b/crates/restorekit-cli/src/commands/restore.rs index 9031a5d..374000f 100644 --- a/crates/restorekit-cli/src/commands/restore.rs +++ b/crates/restorekit-cli/src/commands/restore.rs @@ -190,11 +190,14 @@ fn restore_device(device: &Device, opts: Opts) -> Result<()> { say(json, "Starting restore. Do not disconnect the target."); // The restore-mode USB interface needs our WinUSB forced onto it, which is // done by an elevated watcher the restore spawns — warn about the UAC prompt. + // Apple's usbmuxd, when running, handles restore mode itself. #[cfg(target_os = "windows")] - say( - json, - " A Windows (UAC) prompt will appear to set up restore-mode USB access — approve it.", - ); + if !restorekit::usbmuxd::apple_usbmuxd_running() { + say( + json, + " A Windows (UAC) prompt will appear to set up restore-mode USB access — approve it.", + ); + } // In verbose mode idevicerestore's log streams to the terminal, so hide the // progress bar to avoid interleaving with it. let bar = if json || opts.verbose { diff --git a/crates/restorekit/Cargo.toml b/crates/restorekit/Cargo.toml index d0a2f09..38ea195 100644 --- a/crates/restorekit/Cargo.toml +++ b/crates/restorekit/Cargo.toml @@ -41,6 +41,8 @@ windows-sys = { version = "0.60", features = [ "Win32_Devices_DeviceAndDriverInstallation", "Win32_Foundation", "Win32_Security", + "Win32_Storage_FileSystem", + "Win32_System_IO", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_Shell", diff --git a/crates/restorekit/src/device.rs b/crates/restorekit/src/device.rs index c88d0cc..94f3eca 100644 --- a/crates/restorekit/src/device.rs +++ b/crates/restorekit/src/device.rs @@ -1003,13 +1003,17 @@ pub(crate) fn from_usb(info: &nusb::DeviceInfo) -> Device { } } -/// Whether the OS driver lets restorekit open this device. Only the -/// restore-family modes need WinUSB on Windows; never poke a normal device. +/// Whether the OS driver lets restorekit reach this device: WinUSB, or Apple's +/// own DFU (`WUDFRd`) and KIS drivers, which libirecovery's Windows backend +/// talks to directly. Never poke a normal device. #[cfg(target_os = "windows")] fn driver_ready(info: &nusb::DeviceInfo, mode: UsbMode) -> bool { + let apple = info + .driver() + .is_some_and(|d| d.eq_ignore_ascii_case("WUDFRd") || d.eq_ignore_ascii_case("AppleKIS")); match mode { UsbMode::Other => true, - _ => info.open().wait().is_ok(), + _ => apple || info.open().wait().is_ok(), } } #[cfg(not(target_os = "windows"))] diff --git a/crates/restorekit/src/kis.rs b/crates/restorekit/src/kis.rs index 42d28a0..ee0ebb2 100644 --- a/crates/restorekit/src/kis.rs +++ b/crates/restorekit/src/kis.rs @@ -100,6 +100,13 @@ pub(crate) fn identify(info: &nusb::DeviceInfo) -> Read { } fn read(info: &nusb::DeviceInfo) -> Read { + #[cfg(target_os = "windows")] + if info + .driver() + .is_some_and(|d| d.eq_ignore_ascii_case("AppleKIS")) + { + return apple_kis::read(info); + } match get_info(info) { Ok(reply) => classify(&reply), Err(_) => Read::Failed, @@ -209,6 +216,155 @@ fn hexdump(out: &mut String, bytes: &[u8]) { } } +/// Windows with Apple's own AppleKIS driver bound (Windows Update installs it +/// with the first Apple device). AppleKIS enables the device itself and exposes +/// it as a `KIS\VID_05AC&PID_0001` child that answers a GET_INFO ioctl with the +/// identity string, the way libirecovery's Windows backend reads it. A device +/// that AppleKIS failed to enable has no such child until it re-enters DFU. +#[cfg(target_os = "windows")] +mod apple_kis { + use std::os::windows::ffi::OsStrExt; + use std::ptr::{null, null_mut}; + + use windows_sys::core::GUID; + use windows_sys::Win32::Devices::DeviceAndDriverInstallation::{ + CM_Get_Child, CM_Get_Device_IDW, CM_Get_Device_Interface_ListW, + CM_Get_Device_Interface_List_SizeW, CM_Locate_DevNodeW, + CM_GET_DEVICE_INTERFACE_LIST_PRESENT, CM_LOCATE_DEVNODE_NORMAL, CR_SUCCESS, + }; + use windows_sys::Win32::Foundation::{ + CloseHandle, GetLastError, ERROR_IO_PENDING, GENERIC_READ, GENERIC_WRITE, + INVALID_HANDLE_VALUE, WAIT_OBJECT_0, + }; + use windows_sys::Win32::Storage::FileSystem::{ + CreateFileW, FILE_FLAG_OVERLAPPED, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING, + }; + use windows_sys::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + use windows_sys::Win32::System::IO::{ + CancelIo, DeviceIoControl, GetOverlappedResult, OVERLAPPED, + }; + + use super::Read; + + const GUID_DEVINTERFACE_KIS: GUID = GUID::from_u128(0xb36f4137_f4ef_4bfc_a25a_c2410768ee37); + const IOCTL_GET_INFO: u32 = 0x220004; + /// The reply: vid, pid, a word, then four 255-byte strings (nonces, serial, + /// manufacturer, product). + const FIELD: usize = 255; + const SERIAL_OFFSET: usize = 8 + FIELD; + const INFO_SIZE: usize = 8 + 4 * FIELD; + + pub(super) fn read(info: &nusb::DeviceInfo) -> Read { + match get_info(info) { + Some(reply) => classify(&reply), + None => Read::Failed, + } + } + + fn classify(reply: &[u8]) -> Read { + let field = &reply[SERIAL_OFFSET..SERIAL_OFFSET + FIELD]; + let end = field.iter().position(|&b| b == 0).unwrap_or(FIELD); + let serial = String::from_utf8_lossy(&field[..end]).trim().to_string(); + if serial.is_empty() { + Read::NotInDfu + } else { + Read::Serial(serial) + } + } + + /// The KIS interface path of the AppleKIS child under `info`. + fn interface_path(info: &nusb::DeviceInfo) -> Option> { + let id: Vec = info.instance_id().encode_wide().chain([0]).collect(); + unsafe { + let mut dev = 0; + if CM_Locate_DevNodeW(&mut dev, id.as_ptr(), CM_LOCATE_DEVNODE_NORMAL) != CR_SUCCESS { + return None; + } + let mut child = 0; + if CM_Get_Child(&mut child, dev, 0) != CR_SUCCESS { + return None; + } + let mut child_id = [0u16; 512]; + if CM_Get_Device_IDW(child, child_id.as_mut_ptr(), child_id.len() as u32, 0) + != CR_SUCCESS + { + return None; + } + let mut len = 0; + if CM_Get_Device_Interface_List_SizeW( + &mut len, + &GUID_DEVINTERFACE_KIS, + child_id.as_ptr(), + CM_GET_DEVICE_INTERFACE_LIST_PRESENT, + ) != CR_SUCCESS + { + return None; + } + let mut list = vec![0u16; len as usize]; + if CM_Get_Device_Interface_ListW( + &GUID_DEVINTERFACE_KIS, + child_id.as_ptr(), + list.as_mut_ptr(), + len, + CM_GET_DEVICE_INTERFACE_LIST_PRESENT, + ) != CR_SUCCESS + { + return None; + } + let end = list.iter().position(|&c| c == 0).filter(|&e| e > 0)?; + list.truncate(end + 1); + Some(list) + } + } + + fn get_info(info: &nusb::DeviceInfo) -> Option> { + let path = interface_path(info)?; + let timeout_ms = super::TIMEOUT.as_millis() as u32; + unsafe { + let handle = CreateFileW( + path.as_ptr(), + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + null(), + OPEN_EXISTING, + FILE_FLAG_OVERLAPPED, + null_mut(), + ); + if handle == INVALID_HANDLE_VALUE { + return None; + } + let mut reply = vec![0u8; INFO_SIZE]; + let mut ov: OVERLAPPED = std::mem::zeroed(); + ov.hEvent = CreateEventW(null(), 1, 0, null()); + let mut got = 0u32; + let mut ok = !ov.hEvent.is_null() + && DeviceIoControl( + handle, + IOCTL_GET_INFO, + null(), + 0, + reply.as_mut_ptr().cast(), + INFO_SIZE as u32, + null_mut(), + &mut ov, + ) != 0; + if !ok && !ov.hEvent.is_null() && GetLastError() == ERROR_IO_PENDING { + if WaitForSingleObject(ov.hEvent, timeout_ms) != WAIT_OBJECT_0 { + CancelIo(handle); + } + ok = GetOverlappedResult(handle, &ov, &mut got, 1) != 0; + } else if ok { + GetOverlappedResult(handle, &ov, &mut got, 0); + } + if !ov.hEvent.is_null() { + CloseHandle(ov.hEvent); + } + CloseHandle(handle); + (ok && got as usize >= SERIAL_OFFSET + FIELD).then_some(reply) + } + } +} + /// A KIS portal: a bulk OUT/IN endpoint pair. #[cfg(not(target_os = "macos"))] struct Portal { diff --git a/crates/restorekit/src/restore.rs b/crates/restorekit/src/restore.rs index a2d7ba9..802693c 100644 --- a/crates/restorekit/src/restore.rs +++ b/crates/restorekit/src/restore.rs @@ -254,8 +254,18 @@ pub fn restore( // can reach USB devices (restore mode) without an external daemon — unless a // parent process already started a shared one (parallel restores), which we // then reuse via the inherited USBMUXD_SOCKET_ADDRESS. + // + // On Windows, Apple's own usbmuxd (Apple Mobile Device Service, installed + // with iTunes or Apple Devices) may already hold that port. It drives the + // restore-mode interface through Apple's driver, so use it as-is: no + // embedded server and no WinUSB watcher. + #[cfg(target_os = "windows")] + let apple_usbmuxd = std::env::var_os("RESTOREKIT_SHARED_USBMUXD").is_none() + && crate::usbmuxd::apple_usbmuxd_running(); + #[cfg(target_os = "linux")] + let apple_usbmuxd = false; #[cfg(any(target_os = "linux", target_os = "windows"))] - let _usbmuxd = if std::env::var_os("RESTOREKIT_SHARED_USBMUXD").is_some() { + let _usbmuxd = if apple_usbmuxd || std::env::var_os("RESTOREKIT_SHARED_USBMUXD").is_some() { None } else { Some(crate::usbmuxd::UsbmuxdGuard::start(progress)?) @@ -267,14 +277,18 @@ pub fn restore( // Without it the restore would run for minutes and then stall waiting for // restore mode, so stop now instead. #[cfg(target_os = "windows")] - let _restore_watcher = crate::driver::spawn_restore_mode_watcher().ok_or_else(|| { - Error::DriverInstall( - "couldn't start the restore-mode USB helper (was the Windows UAC prompt \ - declined?). Without it the restore stalls once the Mac enters restore mode; \ - retry and approve the prompt" - .into(), - ) - })?; + let _restore_watcher = if apple_usbmuxd { + None + } else { + Some(crate::driver::spawn_restore_mode_watcher().ok_or_else(|| { + Error::DriverInstall( + "couldn't start the restore-mode USB helper (was the Windows UAC prompt \ + declined?). Without it the restore stalls once the Mac enters restore mode; \ + retry and approve the prompt" + .into(), + ) + })?) + }; let mut attempt = 1; loop { diff --git a/crates/restorekit/src/usbmuxd.rs b/crates/restorekit/src/usbmuxd.rs index aa63e88..6ce0262 100644 --- a/crates/restorekit/src/usbmuxd.rs +++ b/crates/restorekit/src/usbmuxd.rs @@ -12,6 +12,14 @@ use std::thread::{self, JoinHandle}; use crate::error::{Error, Result}; use crate::progress::{Event, ProgressFn}; +/// Whether Apple's usbmuxd (Apple Mobile Device Service) is listening on +/// `127.0.0.1:27015`, the port the embedded server would take. +#[cfg(target_os = "windows")] +pub fn apple_usbmuxd_running() -> bool { + let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 27015)); + std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(300)).is_ok() +} + /// RAII guard that starts the embedded usbmuxd server and tears it down on drop. pub struct UsbmuxdGuard { /// The Unix socket file to clean up (Linux only). diff --git a/docs/windows-restore.md b/docs/windows-restore.md index 4d39193..e69c189 100644 --- a/docs/windows-restore.md +++ b/docs/windows-restore.md @@ -80,13 +80,26 @@ BaseSystem → recovered. The restore-mode phase needed three pieces: streams `Cryptex1,systemOS` at ~35 MB/s (near USB-2.0 line rate) — the embedded usbmuxd + WinUSB bulk path is not a bottleneck. +- **Driverless with Apple's stack.** Windows Update installs Apple's drivers + for DFU (`WUDFRd`), recovery and KIS (`AppleKIS`) on first plug-in, and + libirecovery's native Windows backend talks to them directly. When Apple + Mobile Device Service (iTunes or Apple Devices) is also running, it already + holds `127.0.0.1:27015` and muxes the restore-mode interface through Apple's + driver, so restorekit uses it instead of starting the embedded usbmuxd and the + WinUSB watcher. restorekit reads a KIS Mac's identity through AppleKIS's + GET_INFO ioctl, and counts Apple's drivers as ready. Hardware-tested: a full + revive of an M4 mac mini (KIS DFU via a dongle) on Windows 11 ARM64 with no + RestoreKit driver package installed, no UAC prompt, and no test signing. + AppleKIS only enables a device it saw arrive fresh in DFU; one that WinUSB or + a restart touched first needs to re-enter DFU. + ### Known issues - **Windows on ARM.** Code Integrity rejects our self-signed catalog there ("Driver package signer is not trusted by system, and Code Integrity is enforced"), so `setup-driver` can't stage the package unless test signing is - on (`bcdedit /set testsigning on`). Everything else, including the x64 build - under emulation, works once it's staged. + on (`bcdedit /set testsigning on`). With Apple Mobile Device Service installed + no package is needed (see above). - **Desktop app throughput.** The same restore that runs at ~35 MB/s from the CLI is much slower in the desktop app (the muxer gets fed at only tens of From 6ce82827accd2503f81e3cff56ed5f2572e25251 Mon Sep 17 00:00:00 2001 From: "Frank Chiarulli Jr." Date: Tue, 17 Nov 2026 11:51:09 -0400 Subject: [PATCH 06/10] Harden the Apple driver path on Windows - Only use the usbmuxd port when Apple Mobile Device Service owns it, matching the listener's pid against the service's. Any other listener (another restorekit restore, say) fails the restore up front by name. - With a dongle, put a Mac back into DFU (up to twice) when it lands in KIS DFU unreadable. AppleKIS leaves the interface disabled about half the time when entering DFU from a booted Mac, until it re-enters DFU. - Forget cached KIS sightings for devices that left the bus. Windows reuses the device id, so a re-entry got no arrival grace period. - setup-driver leaves devices on Apple's drivers alone and counts them as set up; moving a KIS Mac off AppleKIS strands it. - Windows on ARM: stop a restore that has neither Apple's service nor a staged package before it starts, and point setup-driver failures there at Apple Devices or iTunes. - Unit tests for the AppleKIS reply and TCP table parsing. --- crates/restorekit-cli/src/commands/dfu.rs | 8 +- crates/restorekit-cli/src/commands/restore.rs | 2 +- .../src/commands/setup_driver.rs | 2 +- crates/restorekit/Cargo.toml | 4 + crates/restorekit/src/device.rs | 11 +- crates/restorekit/src/dfu/trigger.rs | 48 +++++ crates/restorekit/src/driver.rs | 61 +++++- crates/restorekit/src/error.rs | 9 +- crates/restorekit/src/kis.rs | 94 ++++++--- crates/restorekit/src/restore.rs | 27 ++- crates/restorekit/src/usbmuxd.rs | 181 +++++++++++++++++- docs/windows-restore.md | 49 +++-- 12 files changed, 436 insertions(+), 60 deletions(-) diff --git a/crates/restorekit-cli/src/commands/dfu.rs b/crates/restorekit-cli/src/commands/dfu.rs index aeff84b..f28d6ea 100644 --- a/crates/restorekit-cli/src/commands/dfu.rs +++ b/crates/restorekit-cli/src/commands/dfu.rs @@ -379,8 +379,12 @@ pub(crate) fn ensure_present( return select_from(present, json); } // Already in DFU over Debug USB but unreadable here: triggering again - // can't help. - if device::list()?.iter().any(Device::kis_unreadable) { + // can't help, except on Windows with a dongle, which puts it back into + // DFU so Windows' driver picks it up. + if device::list()?.iter().any(Device::kis_unreadable) + && !(cfg!(target_os = "windows") + && restorekit::dongle::list().is_ok_and(|d| d.len() == 1)) + { return Err(Error::KisUnreadable); } // Name a target visible in another mode so the user knows the trigger diff --git a/crates/restorekit-cli/src/commands/restore.rs b/crates/restorekit-cli/src/commands/restore.rs index 374000f..ae53d18 100644 --- a/crates/restorekit-cli/src/commands/restore.rs +++ b/crates/restorekit-cli/src/commands/restore.rs @@ -192,7 +192,7 @@ fn restore_device(device: &Device, opts: Opts) -> Result<()> { // done by an elevated watcher the restore spawns — warn about the UAC prompt. // Apple's usbmuxd, when running, handles restore mode itself. #[cfg(target_os = "windows")] - if !restorekit::usbmuxd::apple_usbmuxd_running() { + if matches!(restorekit::restore::windows_mux_check(), Ok(false)) { say( json, " A Windows (UAC) prompt will appear to set up restore-mode USB access — approve it.", diff --git a/crates/restorekit-cli/src/commands/setup_driver.rs b/crates/restorekit-cli/src/commands/setup_driver.rs index 6e74c0c..9383d03 100644 --- a/crates/restorekit-cli/src/commands/setup_driver.rs +++ b/crates/restorekit-cli/src/commands/setup_driver.rs @@ -92,7 +92,7 @@ fn install(json: bool) -> Result { if json { render::emit_json(&e); } else if let Event::DriverBound { name } = &e { - println!(" bound WinUSB to {name}"); + println!(" USB access ready for {name}"); } }; driver::install_winusb(&mut on_event) diff --git a/crates/restorekit/Cargo.toml b/crates/restorekit/Cargo.toml index 38ea195..f998367 100644 --- a/crates/restorekit/Cargo.toml +++ b/crates/restorekit/Cargo.toml @@ -40,10 +40,14 @@ core-foundation = "0.10" windows-sys = { version = "0.60", features = [ "Win32_Devices_DeviceAndDriverInstallation", "Win32_Foundation", + "Win32_NetworkManagement_IpHelper", + "Win32_Networking_WinSock", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Registry", + "Win32_System_Services", + "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging", diff --git a/crates/restorekit/src/device.rs b/crates/restorekit/src/device.rs index 94f3eca..e3324f0 100644 --- a/crates/restorekit/src/device.rs +++ b/crates/restorekit/src/device.rs @@ -1025,11 +1025,14 @@ fn driver_ready(_info: &nusb::DeviceInfo, _mode: UsbMode) -> bool { /// call [`identify`] to fill in the richer fields (model, ECID, marketing name, /// DFU-port). pub fn list() -> Result> { - let infos = nusb::list_devices().wait().map_err(Error::from)?; - Ok(infos + let infos: Vec = nusb::list_devices() + .wait() + .map_err(Error::from)? .filter(|i| i.vendor_id() == APPLE_VID) - .map(|i| from_usb(&i)) - .collect()) + .collect(); + let ids: Vec = infos.iter().map(nusb::DeviceInfo::id).collect(); + crate::kis::forget_absent(&ids); + Ok(infos.iter().map(from_usb).collect()) } /// Which device to pick. diff --git a/crates/restorekit/src/dfu/trigger.rs b/crates/restorekit/src/dfu/trigger.rs index dfd0c21..09f0e7b 100644 --- a/crates/restorekit/src/dfu/trigger.rs +++ b/crates/restorekit/src/dfu/trigger.rs @@ -84,6 +84,13 @@ const TRIGGER_ATTEMPTS: u32 = 3; /// How long to wait for DFU enumeration before concluding the target booted /// normally and re-sending the trigger. const RETRY_AFTER: Duration = Duration::from_secs(10); +/// Pause between rebooting a Mac out of an unreadable DFU and triggering DFU +/// again (Windows). +#[cfg(target_os = "windows")] +const REDFU_SETTLE: Duration = Duration::from_secs(3); +/// How many times to put an unreadable Mac back into DFU (Windows). +#[cfg(target_os = "windows")] +const REDFU_ATTEMPTS: u32 = 2; /// Trigger DFU on the selected target, routing through a dongle or the host, /// retrying, and (when observable) waiting for the Mac to enter DFU. @@ -216,6 +223,47 @@ fn trigger_via_dongle( want_ecid: Option, timeout: Duration, progress: ProgressFn, +) -> Result { + // Windows' Debug USB driver (AppleKIS) only picks up a Mac that arrives in + // DFU. One it missed (already in DFU when Windows Update installed the + // driver, or after a driver change) reads again after one more DFU entry, + // which the dongle can do: reboot it out of DFU, then trigger again. + #[cfg(target_os = "windows")] + { + fn redfu(d: &Dongle, progress: ProgressFn) -> Result<()> { + progress(Event::DfuTriggerStage { + stage: "Windows didn't pick up the Mac in DFU; putting it back into DFU".into(), + }); + reboot_via_dongle(d, progress)?; + // Triggering straight after the reboot lands it back in DFU but + // unreadable again; give the port a moment to settle first. + std::thread::sleep(REDFU_SETTLE); + Ok(()) + } + let mut redfus = 0; + if device::list()?.iter().any(Device::kis_unreadable) { + redfu(d, progress)?; + redfus += 1; + } + loop { + match trigger_via_dongle_once(d, want_ecid, timeout, progress)? { + DfuOutcome::Entered(dev) if dev.kis_unreadable() && redfus < REDFU_ATTEMPTS => { + redfu(d, progress)?; + redfus += 1; + } + outcome => return Ok(outcome), + } + } + } + #[cfg(not(target_os = "windows"))] + trigger_via_dongle_once(d, want_ecid, timeout, progress) +} + +fn trigger_via_dongle_once( + d: &Dongle, + want_ecid: Option, + timeout: Duration, + progress: ProgressFn, ) -> Result { let mut watch = discovery::watch()?; let deadline = Instant::now() + timeout; diff --git a/crates/restorekit/src/driver.rs b/crates/restorekit/src/driver.rs index 833a109..eda6ec6 100644 --- a/crates/restorekit/src/driver.rs +++ b/crates/restorekit/src/driver.rs @@ -53,6 +53,43 @@ pub fn is_target_pid(pid: u16) -> bool { DRIVER_PIDS.contains(&pid) } +/// What to tell Windows on ARM users, where restorekit's own driver package +/// can't be installed. +pub const ARM64_HINT: &str = "Windows on ARM only loads Microsoft-signed driver packages, so \ + restorekit can't install its own USB driver here. Install Apple Devices from the Microsoft \ + Store (or iTunes) instead and retry: restorekit then uses Apple's drivers and Apple Mobile \ + Device Service, and needs no driver of its own"; + +/// Whether Windows itself runs on ARM64, including when this x64 build runs +/// under emulation there. +#[cfg(target_os = "windows")] +pub fn native_arm64() -> bool { + use windows_sys::Win32::System::SystemInformation::IMAGE_FILE_MACHINE_ARM64; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, IsWow64Process2}; + let (mut process, mut native) = (0u16, 0u16); + let ok = unsafe { IsWow64Process2(GetCurrentProcess(), &mut process, &mut native) != 0 }; + ok && native == IMAGE_FILE_MACHINE_ARM64 +} + +/// Whether our WinUSB package is in the driver store (the restore-mode watcher +/// binds the newest one). +#[cfg(target_os = "windows")] +pub fn winusb_package_staged() -> bool { + let Some(windir) = std::env::var_os("windir") else { + return false; + }; + let Ok(entries) = std::fs::read_dir(std::path::Path::new(&windir).join("INF")) else { + return false; + }; + entries.flatten().any(|e| { + let name = e.file_name().to_string_lossy().to_ascii_lowercase(); + name.starts_with("oem") + && name.ends_with(".inf") + && std::fs::read_to_string(e.path()) + .is_ok_and(|c| c.contains("RestoreKit") && c.contains("RESTORE_MODE")) + }) +} + /// A connected Apple device that needs WinUSB bound before restorekit can use it. #[derive(Debug, Clone)] pub struct Target { @@ -178,7 +215,12 @@ pub fn install_winusb(progress: ProgressFn) -> Result { } progress(Event::DriverSetupStarting); - run_setup_script(false)?; + run_setup_script(false).map_err(|e| match e { + Error::DriverInstall(detail) if native_arm64() => { + Error::DriverInstall(format!("{ARM64_HINT}\n\n{detail}")) + } + e => e, + })?; for t in &targets { progress(Event::DriverBound { @@ -474,9 +516,17 @@ public static class RkNewDev { $staged = Join-Path $env:windir "INF\$leaf" $devices = Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | Where-Object { $_.InstanceId -match $DeviceRegex } +# Apple's own drivers (Windows Update, iTunes, Apple Devices) already work with +# restorekit, and moving a KIS Mac off AppleKIS strands it until it re-enters +# DFU, so only bind devices on no driver or someone else's. +function Test-AppleDriver($id) { + $provider = (Get-PnpDeviceProperty -InstanceId $id -KeyName DEVPKEY_Device_DriverProvider -ErrorAction SilentlyContinue).Data + return ($provider -match '^Apple') +} foreach ($dev in $devices) { $infNow = (Get-PnpDeviceProperty -InstanceId $dev.InstanceId -KeyName DEVPKEY_Device_DriverInfPath -ErrorAction SilentlyContinue).Data if ($infNow -eq $leaf) { continue } + if (Test-AppleDriver $dev.InstanceId) { continue } # INSTALLFLAG_FORCE (0x1) | INSTALLFLAG_NONINTERACTIVE (0x4). $hwid = $dev.InstanceId -replace '\\[^\\]+$', '' $reboot = $false @@ -485,10 +535,13 @@ foreach ($dev in $devices) { Write-Output ("could not bind {0} (was {1}): error 0x{2:X8}" -f $dev.InstanceId, $infNow, $code) } } -$svcs = Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | +$ready = Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | Where-Object { $_.InstanceId -match $DeviceRegex } | - ForEach-Object { (Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName 'DEVPKEY_Device_Service' -ErrorAction SilentlyContinue).Data } -if ($svcs -contains 'WINUSB' -or $svcs -contains 'winusb') { exit 0 } + Where-Object { + (Test-AppleDriver $_.InstanceId) -or + (Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName 'DEVPKEY_Device_Service' -ErrorAction SilentlyContinue).Data -eq 'WINUSB' + } +if ($ready) { exit 0 } Write-Error 'WinUSB was not bound to any connected device' exit 1 "#; diff --git a/crates/restorekit/src/error.rs b/crates/restorekit/src/error.rs index 3eba888..a1c7e0a 100644 --- a/crates/restorekit/src/error.rs +++ b/crates/restorekit/src/error.rs @@ -125,10 +125,11 @@ fn kis_unreadable_message() -> &'static str { shows up, so retrying without re-entering DFU won't help" } else if cfg!(target_os = "windows") { "the Mac is in DFU over Apple's Debug USB interface (05ac:1881), but restorekit couldn't \ - read its identity. Run `restorekit setup-driver` so WinUSB is bound to it, then put the \ - Mac back into DFU (`restorekit reboot`, then `restorekit dfu`) and retry. Windows Update \ - installs Apple's own driver for it, and once that driver has had the Mac it only works \ - again after re-entering DFU" + read its identity. Windows' driver for it only picks up a Mac that arrives in DFU, so \ + one that was already there when the driver was installed or changed stays unreadable. \ + Put the Mac back into DFU (`restorekit reboot`, then `restorekit dfu`; with a dongle \ + restorekit does this itself) and retry. If it still can't be read, run \ + `restorekit setup-driver`" } else { "the Mac is in DFU over Apple's Debug USB interface (05ac:1881), but restorekit couldn't \ read its identity. Check USB permissions (the udev rule covers 05ac:1881) and retry" diff --git a/crates/restorekit/src/kis.rs b/crates/restorekit/src/kis.rs index ee0ebb2..4684b2b 100644 --- a/crates/restorekit/src/kis.rs +++ b/crates/restorekit/src/kis.rs @@ -67,15 +67,28 @@ pub(crate) enum Read { /// arrival, so the first request can land before it's ready. const ARRIVAL_GRACE: Duration = Duration::from_secs(3); +/// When each KIS device was first seen, and its identity once read. +type Seen = HashMap)>; + +fn seen() -> &'static Mutex { + static SEEN: OnceLock> = OnceLock::new(); + SEEN.get_or_init(Default::default) +} + +/// Drop what [`identify`] remembers about devices no longer on the bus. Device +/// ids can come back for the same port (Windows reuses the device instance), and +/// a Mac re-entering DFU there is a new arrival that needs its own grace period +/// and its own read. +pub(crate) fn forget_absent(present: &[nusb::DeviceId]) { + seen().lock().unwrap().retain(|id, _| present.contains(id)); +} + /// Read the KIS device behind `info`. A good identity is cached per /// enumeration, so polling `list()` asks each device once; anything else is /// asked again on the next call, so a device that finishes coming up (or a /// daemon that finishes attaching) isn't stuck with its first answer. pub(crate) fn identify(info: &nusb::DeviceInfo) -> Read { - // When each device was first seen, and its identity once read. - type Seen = HashMap)>; - static SEEN: OnceLock> = OnceLock::new(); - let seen = SEEN.get_or_init(Default::default); + let seen = seen(); let first_seen = { let mut seen = seen.lock().unwrap(); let entry = seen.entry(info.id()).or_insert((Instant::now(), None)); @@ -216,6 +229,33 @@ fn hexdump(out: &mut String, bytes: &[u8]) { } } +/// AppleKIS's GET_INFO reply: vid, pid, a word, then four 255-byte strings +/// (nonces, serial, manufacturer, product), as libirecovery declares it. +#[cfg(any(target_os = "windows", test))] +const APPLE_KIS_FIELD: usize = 255; +#[cfg(any(target_os = "windows", test))] +const APPLE_KIS_SERIAL_OFFSET: usize = 8 + APPLE_KIS_FIELD; +#[cfg(any(target_os = "windows", test))] +const APPLE_KIS_SERIAL_END: usize = APPLE_KIS_SERIAL_OFFSET + APPLE_KIS_FIELD; +#[cfg(any(target_os = "windows", test))] +const APPLE_KIS_INFO_SIZE: usize = 8 + 4 * APPLE_KIS_FIELD; + +/// The identity string out of an AppleKIS GET_INFO reply. An empty serial +/// means the chip behind the port isn't in DFU. +#[cfg(any(target_os = "windows", test))] +fn classify_apple_kis(reply: &[u8]) -> Read { + let Some(field) = reply.get(APPLE_KIS_SERIAL_OFFSET..APPLE_KIS_SERIAL_END) else { + return Read::Failed; + }; + let end = field.iter().position(|&b| b == 0).unwrap_or(field.len()); + let serial = String::from_utf8_lossy(&field[..end]).trim().to_string(); + if serial.is_empty() { + Read::NotInDfu + } else { + Read::Serial(serial) + } +} + /// Windows with Apple's own AppleKIS driver bound (Windows Update installs it /// with the first Apple device). AppleKIS enables the device itself and exposes /// it as a `KIS\VID_05AC&PID_0001` child that answers a GET_INFO ioctl with the @@ -246,32 +286,18 @@ mod apple_kis { use super::Read; + use super::{classify_apple_kis, APPLE_KIS_INFO_SIZE as INFO_SIZE, APPLE_KIS_SERIAL_END}; + const GUID_DEVINTERFACE_KIS: GUID = GUID::from_u128(0xb36f4137_f4ef_4bfc_a25a_c2410768ee37); const IOCTL_GET_INFO: u32 = 0x220004; - /// The reply: vid, pid, a word, then four 255-byte strings (nonces, serial, - /// manufacturer, product). - const FIELD: usize = 255; - const SERIAL_OFFSET: usize = 8 + FIELD; - const INFO_SIZE: usize = 8 + 4 * FIELD; pub(super) fn read(info: &nusb::DeviceInfo) -> Read { match get_info(info) { - Some(reply) => classify(&reply), + Some(reply) => classify_apple_kis(&reply), None => Read::Failed, } } - fn classify(reply: &[u8]) -> Read { - let field = &reply[SERIAL_OFFSET..SERIAL_OFFSET + FIELD]; - let end = field.iter().position(|&b| b == 0).unwrap_or(FIELD); - let serial = String::from_utf8_lossy(&field[..end]).trim().to_string(); - if serial.is_empty() { - Read::NotInDfu - } else { - Read::Serial(serial) - } - } - /// The KIS interface path of the AppleKIS child under `info`. fn interface_path(info: &nusb::DeviceInfo) -> Option> { let id: Vec = info.instance_id().encode_wide().chain([0]).collect(); @@ -360,7 +386,7 @@ mod apple_kis { CloseHandle(ov.hEvent); } CloseHandle(handle); - (ok && got as usize >= SERIAL_OFFSET + FIELD).then_some(reply) + (ok && got as usize >= APPLE_KIS_SERIAL_END).then_some(reply) } } } @@ -699,6 +725,30 @@ mod dic { mod tests { use super::*; + fn apple_kis_reply(serial: &str) -> Vec { + let mut reply = vec![0u8; APPLE_KIS_INFO_SIZE]; + reply[..4].copy_from_slice(&[0xac, 0x05, 0x27, 0x12]); + reply[8..8 + 5].copy_from_slice(b"NONC:"); + reply[APPLE_KIS_SERIAL_OFFSET..APPLE_KIS_SERIAL_OFFSET + serial.len()] + .copy_from_slice(serial.as_bytes()); + reply + } + + #[test] + fn reads_serial_from_apple_kis_reply() { + let serial = "SDOM:01 CPID:8132 BDID:2A ECID:000A78D20A06401C SRTG:[iBoot-9082.0.0.300.1]"; + assert_eq!( + classify_apple_kis(&apple_kis_reply(serial)), + Read::Serial(serial.to_string()) + ); + } + + #[test] + fn empty_apple_kis_serial_means_not_in_dfu() { + assert_eq!(classify_apple_kis(&apple_kis_reply("")), Read::NotInDfu); + assert_eq!(classify_apple_kis(&[0u8; 16]), Read::Failed); + } + #[test] fn header_matches_libirecovery() { // GET_INFO on the RSM portal, 0xC0 reply words, no args. diff --git a/crates/restorekit/src/restore.rs b/crates/restorekit/src/restore.rs index 802693c..7f9270c 100644 --- a/crates/restorekit/src/restore.rs +++ b/crates/restorekit/src/restore.rs @@ -235,6 +235,29 @@ fn with_failure_hint(err: Error) -> Error { } } +/// Decide who serves restore mode on Windows before the restore starts, so a +/// setup that can't reach it fails now rather than after the uploads. Returns +/// whether Apple's usbmuxd is the one to use (no UAC prompt then). +#[cfg(target_os = "windows")] +pub fn windows_mux_check() -> Result { + use crate::usbmuxd::MuxPort; + match crate::usbmuxd::mux_port() { + MuxPort::Apple => Ok(true), + MuxPort::Other { pid, name } => Err(Error::UsbmuxdFailed(format!( + "another program ({}) is listening on 127.0.0.1:27015, the port restorekit's \ + USB mux uses. If it's another restorekit restore, wait for it to finish; \ + otherwise close it and retry", + name.unwrap_or_else(|| format!("pid {pid}")) + ))), + MuxPort::Free + if crate::driver::native_arm64() && !crate::driver::winusb_package_staged() => + { + Err(Error::DriverInstall(crate::driver::ARM64_HINT.into())) + } + MuxPort::Free => Ok(false), + } +} + /// Run a restore against the DFU device with the given ECID, streaming progress. /// /// This links libidevicerestore statically; there is no external binary. @@ -260,8 +283,8 @@ pub fn restore( // restore-mode interface through Apple's driver, so use it as-is: no // embedded server and no WinUSB watcher. #[cfg(target_os = "windows")] - let apple_usbmuxd = std::env::var_os("RESTOREKIT_SHARED_USBMUXD").is_none() - && crate::usbmuxd::apple_usbmuxd_running(); + let apple_usbmuxd = + std::env::var_os("RESTOREKIT_SHARED_USBMUXD").is_none() && windows_mux_check()?; #[cfg(target_os = "linux")] let apple_usbmuxd = false; #[cfg(any(target_os = "linux", target_os = "windows"))] diff --git a/crates/restorekit/src/usbmuxd.rs b/crates/restorekit/src/usbmuxd.rs index 6ce0262..4e4dfae 100644 --- a/crates/restorekit/src/usbmuxd.rs +++ b/crates/restorekit/src/usbmuxd.rs @@ -12,12 +12,151 @@ use std::thread::{self, JoinHandle}; use crate::error::{Error, Result}; use crate::progress::{Event, ProgressFn}; -/// Whether Apple's usbmuxd (Apple Mobile Device Service) is listening on -/// `127.0.0.1:27015`, the port the embedded server would take. +/// The loopback port usbmuxd listens on under Windows. +#[cfg(any(target_os = "windows", test))] +const MUX_PORT: u16 = 27015; + +/// Who holds the usbmuxd port on Windows. +#[cfg(target_os = "windows")] +#[derive(Debug, Clone, PartialEq)] +pub enum MuxPort { + /// Nobody: the embedded server can take it. + Free, + /// Apple Mobile Device Service (iTunes, Apple Devices), Apple's own + /// usbmuxd, which drives the restore-mode interface through Apple's driver. + Apple, + /// Some other process, named when we can read it. + Other { pid: u32, name: Option }, +} + +/// Find who listens on the usbmuxd port. Apple's service is told apart by its +/// process id from the service manager, so another restorekit's embedded +/// server (or any other program) isn't mistaken for it. +#[cfg(target_os = "windows")] +pub fn mux_port() -> MuxPort { + match win::listener_pid(MUX_PORT) { + None => MuxPort::Free, + Some(pid) if win::apple_service_pid() == Some(pid) => MuxPort::Apple, + Some(pid) => MuxPort::Other { + pid, + name: win::process_name(pid), + }, + } +} + +/// The pid listening on IPv4 `port` (loopback or any address), from the rows +/// of a `MIB_TCPTABLE_OWNER_PID`: six little-endian words each, with the +/// address and port in network byte order. +#[cfg(any(target_os = "windows", test))] +fn listener_in_rows(rows: &[u8], port: u16) -> Option { + rows.chunks_exact(24).find_map(|row| { + let addr = [row[4], row[5], row[6], row[7]]; + let row_port = u16::from_be_bytes([row[8], row[9]]); + let pid = u32::from_le_bytes([row[20], row[21], row[22], row[23]]); + (row_port == port && (addr == [127, 0, 0, 1] || addr == [0, 0, 0, 0])).then_some(pid) + }) +} + #[cfg(target_os = "windows")] -pub fn apple_usbmuxd_running() -> bool { - let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 27015)); - std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(300)).is_ok() +mod win { + use std::os::windows::ffi::OsStrExt; + use std::ptr::null; + + use windows_sys::Win32::Foundation::{CloseHandle, ERROR_INSUFFICIENT_BUFFER, NO_ERROR}; + use windows_sys::Win32::NetworkManagement::IpHelper::{ + GetExtendedTcpTable, TCP_TABLE_OWNER_PID_LISTENER, + }; + use windows_sys::Win32::Networking::WinSock::AF_INET; + use windows_sys::Win32::System::Services::{ + CloseServiceHandle, OpenSCManagerW, OpenServiceW, QueryServiceStatusEx, SC_MANAGER_CONNECT, + SC_STATUS_PROCESS_INFO, SERVICE_QUERY_STATUS, SERVICE_RUNNING, SERVICE_STATUS_PROCESS, + }; + use windows_sys::Win32::System::Threading::{ + OpenProcess, QueryFullProcessImageNameW, PROCESS_QUERY_LIMITED_INFORMATION, + }; + + /// The service iTunes and Apple Devices install. + const APPLE_SERVICE: &str = "Apple Mobile Device Service"; + + pub(super) fn listener_pid(port: u16) -> Option { + let mut size = 0u32; + let mut buf: Vec = Vec::new(); + for _ in 0..4 { + let rc = unsafe { + GetExtendedTcpTable( + buf.as_mut_ptr().cast(), + &mut size, + 0, + AF_INET as u32, + TCP_TABLE_OWNER_PID_LISTENER, + 0, + ) + }; + match rc { + NO_ERROR => { + let count = u32::from_le_bytes(buf.get(..4)?.try_into().ok()?) as usize; + let rows = buf.get(4..4 + count * 24)?; + return super::listener_in_rows(rows, port); + } + ERROR_INSUFFICIENT_BUFFER => buf = vec![0; size as usize], + _ => return None, + } + } + None + } + + pub(super) fn apple_service_pid() -> Option { + let name: Vec = std::ffi::OsStr::new(APPLE_SERVICE) + .encode_wide() + .chain([0]) + .collect(); + unsafe { + let scm = OpenSCManagerW(null(), null(), SC_MANAGER_CONNECT); + if scm.is_null() { + return None; + } + let svc = OpenServiceW(scm, name.as_ptr(), SERVICE_QUERY_STATUS); + let mut pid = None; + if !svc.is_null() { + let mut status: SERVICE_STATUS_PROCESS = std::mem::zeroed(); + let mut needed = 0; + if QueryServiceStatusEx( + svc, + SC_STATUS_PROCESS_INFO, + (&mut status as *mut SERVICE_STATUS_PROCESS).cast(), + std::mem::size_of::() as u32, + &mut needed, + ) != 0 + && status.dwCurrentState == SERVICE_RUNNING + { + pid = Some(status.dwProcessId); + } + CloseServiceHandle(svc); + } + CloseServiceHandle(scm); + pid + } + } + + /// The executable name of `pid`, when this user may query it (not for + /// services running as SYSTEM, without elevation). + pub(super) fn process_name(pid: u32) -> Option { + unsafe { + let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); + if handle.is_null() { + return None; + } + let mut buf = [0u16; 1024]; + let mut len = buf.len() as u32; + let ok = QueryFullProcessImageNameW(handle, 0, buf.as_mut_ptr(), &mut len) != 0; + CloseHandle(handle); + if !ok { + return None; + } + let path = String::from_utf16_lossy(&buf[..len as usize]); + path.rsplit('\\').next().map(str::to_string) + } + } } /// RAII guard that starts the embedded usbmuxd server and tears it down on drop. @@ -109,3 +248,35 @@ impl Drop for UsbmuxdGuard { } } } + +#[cfg(test)] +mod tests { + use super::*; + + fn row(addr: [u8; 4], port: u16, pid: u32) -> Vec { + let mut r = Vec::new(); + r.extend_from_slice(&2u32.to_le_bytes()); // MIB_TCP_STATE_LISTEN + r.extend_from_slice(&addr); + r.extend_from_slice(&port.to_be_bytes()); + r.extend_from_slice(&[0, 0]); + r.extend_from_slice(&[0; 8]); + r.extend_from_slice(&pid.to_le_bytes()); + r + } + + #[test] + fn finds_the_loopback_or_wildcard_listener() { + let mut rows = row([0, 0, 0, 0], 135, 900); + rows.extend(row([192, 168, 1, 2], MUX_PORT, 1)); + rows.extend(row([127, 0, 0, 1], MUX_PORT, 7760)); + assert_eq!(listener_in_rows(&rows, MUX_PORT), Some(7760)); + assert_eq!( + listener_in_rows(&row([0, 0, 0, 0], MUX_PORT, 42), MUX_PORT), + Some(42) + ); + assert_eq!( + listener_in_rows(&row([0, 0, 0, 0], 135, 900), MUX_PORT), + None + ); + } +} diff --git a/docs/windows-restore.md b/docs/windows-restore.md index e69c189..a53efca 100644 --- a/docs/windows-restore.md +++ b/docs/windows-restore.md @@ -62,12 +62,12 @@ BaseSystem → recovered. The restore-mode phase needed three pieces: elevated watcher now stages the package before it starts watching, logs what it did to `%TEMP%\restorekit-restore-watch.log`, and the restore stops up front if the watcher can't start (UAC declined) instead of stalling later. -- **`setup-driver` forces WinUSB over Apple's drivers.** Windows Update - installs Apple's WHQL-signed `applekis.inf` for a KIS Mac (05ac:1881), which - outranks our self-signed package, so `pnputil /install` left it in place and - restorekit couldn't read the Mac. `setup-driver` now force-binds every present - target like the restore-mode watcher does. A KIS Mac that Apple's driver has - already opened only answers again after re-entering DFU. +- **`setup-driver` leaves Apple's drivers alone.** Windows Update installs + Apple's WHQL-signed drivers (`appleusb.inf`, `applekis.inf`) on first + plug-in, and they work with restorekit (see "Driverless" below). Moving a KIS + Mac off AppleKIS strands it until it re-enters DFU, so `setup-driver` only + binds WinUSB to devices on no driver or a non-Apple one, and counts devices on + Apple's drivers as set up. - **Dongles work on Windows.** The dongle firmware asked for WinUSB but gave no device interface GUID, so Windows never exposed the vendor interface to nusb ("Could not find DeviceInterfaceGUIDs in registry"). The next firmware adds @@ -83,15 +83,28 @@ BaseSystem → recovered. The restore-mode phase needed three pieces: - **Driverless with Apple's stack.** Windows Update installs Apple's drivers for DFU (`WUDFRd`), recovery and KIS (`AppleKIS`) on first plug-in, and libirecovery's native Windows backend talks to them directly. When Apple - Mobile Device Service (iTunes or Apple Devices) is also running, it already - holds `127.0.0.1:27015` and muxes the restore-mode interface through Apple's + Mobile Device Service (iTunes or Apple Devices) is running, it holds + `127.0.0.1:27015` and muxes the restore-mode interface through Apple's driver, so restorekit uses it instead of starting the embedded usbmuxd and the - WinUSB watcher. restorekit reads a KIS Mac's identity through AppleKIS's - GET_INFO ioctl, and counts Apple's drivers as ready. Hardware-tested: a full - revive of an M4 mac mini (KIS DFU via a dongle) on Windows 11 ARM64 with no - RestoreKit driver package installed, no UAC prompt, and no test signing. - AppleKIS only enables a device it saw arrive fresh in DFU; one that WinUSB or - a restart touched first needs to re-enter DFU. + WinUSB watcher. It's recognized by matching the port's listener pid against the + service's pid from the service manager; any other listener on the port fails + the restore up front with its name. restorekit reads a KIS Mac's identity + through AppleKIS's GET_INFO ioctl and counts Apple's drivers as ready. + Hardware-tested: a full revive of an M4 mac mini (KIS DFU via a dongle) on + Windows 11 ARM64 with no RestoreKit driver package, no UAC prompt and no test + signing. +- **AppleKIS sometimes misses the Mac.** Entering KIS DFU from a fully booted + Mac, AppleKIS leaves its interface disabled about half the time (no + `KIS\VID_05AC&PID_0001` child), and the Mac stays unreadable until it + re-enters DFU; restarting the device doesn't help. With a dongle, restorekit + now reboots the Mac out of DFU and triggers again (up to twice) when it lands + unreadable. Measured on the M4 mini: every unreadable entry read fine after + one re-entry. +- **Windows on ARM without Apple's service fails up front.** Our self-signed + package can't be staged there (see Known issues), so a restore with no Apple + Mobile Device Service and no staged package stops before uploading anything + and says to install Apple Devices or iTunes; `setup-driver` failures on ARM + say the same. ### Known issues @@ -99,7 +112,13 @@ BaseSystem → recovered. The restore-mode phase needed three pieces: ("Driver package signer is not trusted by system, and Code Integrity is enforced"), so `setup-driver` can't stage the package unless test signing is on (`bcdedit /set testsigning on`). With Apple Mobile Device Service installed - no package is needed (see above). + no package is needed (see above), but a dongle on firmware 0.1.2 or older + still needs `setup-driver` for its interface GUID; update it from macOS or + Linux. +- **Classic DFU (`05ac:1227`) through Apple's driver is untested here.** The + rig's M4 only enters KIS DFU over the dongle. #56's log shows Port DFU, DFU + and recovery going through libirecovery on Windows, but not which driver was + bound. - **Desktop app throughput.** The same restore that runs at ~35 MB/s from the CLI is much slower in the desktop app (the muxer gets fed at only tens of From 2e6aa207667d8ab5ceb138db8abbf402b2708665 Mon Sep 17 00:00:00 2001 From: "Frank Chiarulli Jr." Date: Tue, 17 Nov 2026 12:34:12 -0400 Subject: [PATCH 07/10] Use as_chunks in the TCP table parser --- crates/restorekit/src/usbmuxd.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/restorekit/src/usbmuxd.rs b/crates/restorekit/src/usbmuxd.rs index 4e4dfae..4abb9af 100644 --- a/crates/restorekit/src/usbmuxd.rs +++ b/crates/restorekit/src/usbmuxd.rs @@ -49,7 +49,7 @@ pub fn mux_port() -> MuxPort { /// address and port in network byte order. #[cfg(any(target_os = "windows", test))] fn listener_in_rows(rows: &[u8], port: u16) -> Option { - rows.chunks_exact(24).find_map(|row| { + rows.as_chunks::<24>().0.iter().find_map(|row| { let addr = [row[4], row[5], row[6], row[7]]; let row_port = u16::from_be_bytes([row[8], row[9]]); let pid = u32::from_le_bytes([row[20], row[21], row[22], row[23]]); From 1eea646925ed257128ae988b9bbd8716a4ca4a97 Mon Sep 17 00:00:00 2001 From: "Frank Chiarulli Jr." Date: Tue, 17 Nov 2026 13:37:39 -0400 Subject: [PATCH 08/10] Build libusb from vendored source on Windows MSYS2 dropped mingw-w64-x86_64-libusb from the MINGW64 repo (only the ucrt64/clang64 builds remain), so the Windows jobs only kept working off the setup action's cached package database. Vendor libusb 1.0.30 as a submodule and build it with the rest of the C stack on Windows, where only the embedded usbmuxd uses it. Linux still links the system libusb. --- .github/workflows/ci.yml | 12 +++++----- .github/workflows/release-app.yml | 4 ++-- .github/workflows/release.yml | 1 - .gitmodules | 4 ++++ crates/restorekit-sys/build.rs | 36 +++++++++++------------------ crates/restorekit-sys/vendor/libusb | 1 + docs/building.md | 5 ++-- 7 files changed, 30 insertions(+), 33 deletions(-) create mode 160000 crates/restorekit-sys/vendor/libusb diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5527048..414e902 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -241,10 +241,10 @@ jobs: # C stack) or rebuilds openssl-src (the target cache has it), so the full # toolbox — base-devel, autotools, perl, cmake, nasm, ~835 MiB — is dead # weight; install only what the warm path uses: gcc + binutils for - # build.rs's cc step and the final link, pkgconf + libusb for the libusb - # probe, and POSIX `patch` (build.rs applies the idevicerestore patches - # with `patch`, not `git apply`). Either cache missing falls back to the - # full set (base-devel already bundles `patch`). + # build.rs's cc step and the final link, pkgconf, and POSIX `patch` + # (build.rs applies the idevicerestore patches with `patch`, not + # `git apply`). Either cache missing falls back to the full set + # (base-devel already bundles `patch`). - uses: msys2/setup-msys2@v2 with: msystem: MINGW64 @@ -255,8 +255,8 @@ jobs: update: false install: >- ${{ (steps.c-stack.outputs.cache-hit == 'true' && steps.rust-cache.outputs.cache-hit == 'true') - && 'git patch mingw-w64-x86_64-gcc mingw-w64-x86_64-pkgconf mingw-w64-x86_64-libusb' - || 'base-devel git make autoconf automake libtool autoconf-archive gettext-devel pkgconf perl mingw-w64-x86_64-gcc mingw-w64-x86_64-pkgconf mingw-w64-x86_64-cmake mingw-w64-x86_64-libusb mingw-w64-x86_64-nasm' }} + && 'git patch mingw-w64-x86_64-gcc mingw-w64-x86_64-pkgconf' + || 'base-devel git make autoconf automake libtool autoconf-archive gettext-devel pkgconf perl mingw-w64-x86_64-gcc mingw-w64-x86_64-pkgconf mingw-w64-x86_64-cmake mingw-w64-x86_64-nasm' }} - name: Test (windows-gnu, static C stack under MSYS2) shell: msys2 {0} diff --git a/.github/workflows/release-app.yml b/.github/workflows/release-app.yml index e649503..acbd854 100644 --- a/.github/workflows/release-app.yml +++ b/.github/workflows/release-app.yml @@ -71,7 +71,7 @@ jobs: base-devel git make autoconf automake libtool autoconf-archive gettext-devel pkgconf perl mingw-w64-x86_64-gcc mingw-w64-x86_64-pkgconf mingw-w64-x86_64-cmake - mingw-w64-x86_64-libusb mingw-w64-x86_64-nasm + mingw-w64-x86_64-nasm - name: Put the MSYS2 toolchain on PATH # tauri-action runs cargo in the default shell, so the C stack's autotools @@ -79,7 +79,7 @@ jobs: # GITHUB_PATH lines are prepended with the LAST-written line taking # precedence, so write usr\bin first: mingw64\bin must end up ahead of it # so `pkg-config` is the MinGW-prefix pkgconf — the one that searches - # /mingw64/lib/pkgconfig (libusb-1.0) and reports native library paths. + # /mingw64/lib/pkgconfig and reports native library paths. if: runner.os == 'Windows' shell: pwsh run: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2f449cb..36ebe4a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -122,7 +122,6 @@ jobs: mingw-w64-x86_64-gcc mingw-w64-x86_64-pkgconf mingw-w64-x86_64-cmake - mingw-w64-x86_64-libusb mingw-w64-x86_64-nasm # GNU host toolchain: build scripts link with ld, not MSVC's link.exe diff --git a/.gitmodules b/.gitmodules index 7479017..f74d26d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -33,3 +33,7 @@ [submodule "crates/restorekit-sys/vendor/usbmuxd"] path = crates/restorekit-sys/vendor/usbmuxd url = https://github.com/libimobiledevice/usbmuxd.git +[submodule "crates/restorekit-sys/vendor/libusb"] + path = crates/restorekit-sys/vendor/libusb + url = https://github.com/libusb/libusb.git + ignore = dirty diff --git a/crates/restorekit-sys/build.rs b/crates/restorekit-sys/build.rs index 51c5b3c..b2d24e9 100644 --- a/crates/restorekit-sys/build.rs +++ b/crates/restorekit-sys/build.rs @@ -75,6 +75,13 @@ fn main() { // idevicerestore talks to for the restore-mode phase. let target_os = env::var("CARGO_CFG_TARGET_OS"); if matches!(target_os.as_deref(), Ok("linux") | Ok("windows")) { + // Linux links the system libusb. MSYS2 no longer packages libusb for + // MINGW64, so on Windows build it from the vendored source; only the + // embedded usbmuxd uses it there (libirecovery talks to Windows + // directly), so it goes after the libimobiledevice family. + if deps.windows { + build_autotools(&vendor.join("libusb"), "libusb", "1.0.30", &deps); + } compile_usbmuxd(&vendor.join("usbmuxd"), &deps); } @@ -661,8 +668,11 @@ fn compile_usbmuxd(src: &Path, deps: &Deps) { .define("HAVE_LOCALTIME_R", None); } - // libusb-1.0 headers (usbmuxd includes directly). - if let Ok(output) = std::process::Command::new("pkg-config") + // libusb-1.0 headers (usbmuxd includes directly): our own build + // on Windows, the system's elsewhere. + if deps.windows { + build.include(deps.prefix.join("include/libusb-1.0")); + } else if let Ok(output) = std::process::Command::new("pkg-config") .args(["--cflags-only-I", "libusb-1.0"]) .output() { @@ -725,12 +735,8 @@ fn emit_link_directives(prefix: &Path) { println!("cargo:rustc-link-lib=framework={fw}"); } } else if target_os.as_deref() == Ok("windows") { - // libusb (static, from MSYS2) plus the Win32 libraries it, libcurl, and - // OpenSSL pull in. libusb-1.0.a lives in the MinGW prefix, not our - // staging dir, so point rustc's linker at that libdir (via pkg-config). - if let Some(libdir) = mingw_libusb_libdir() { - println!("cargo:rustc-link-search=native={libdir}"); - } + // libusb (static, built into our staging prefix) plus the Win32 + // libraries it, libcurl, and OpenSSL pull in. println!("cargo:rustc-link-lib=static=usb-1.0"); for lib in [ "setupapi", "ole32", "ws2_32", "crypt32", "secur32", "bcrypt", "iphlpapi", "userenv", @@ -744,20 +750,6 @@ fn emit_link_directives(prefix: &Path) { } } -/// Ask pkg-config where MSYS2's static libusb (`libusb-1.0.a`) lives, so the -/// final rustc link can find it. Returns a native path rustc's linker accepts. -fn mingw_libusb_libdir() -> Option { - let out = Command::new("pkg-config") - .args(["--variable=libdir", "libusb-1.0"]) - .output() - .ok()?; - if !out.status.success() { - return None; - } - let dir = String::from_utf8_lossy(&out.stdout).trim().to_string(); - (!dir.is_empty()).then_some(dir) -} - /// A Command that runs `script` — directly on Unix, or via MSYS2's `sh` on /// Windows (where Rust's `Command` can't exec a shell script itself). fn shell(windows: bool, script: &str) -> Command { diff --git a/crates/restorekit-sys/vendor/libusb b/crates/restorekit-sys/vendor/libusb new file mode 160000 index 0000000..87a5563 --- /dev/null +++ b/crates/restorekit-sys/vendor/libusb @@ -0,0 +1 @@ +Subproject commit 87a55632db62c9bdc58cd31d3ccfa673f1bb017f diff --git a/docs/building.md b/docs/building.md index 25c9f08..8707288 100644 --- a/docs/building.md +++ b/docs/building.md @@ -15,7 +15,8 @@ idevicerestore via autotools, libzip via CMake, plus OpenSSL/curl/zlib through vendored `-sys` crates. So `cargo install` / `cargo build` need **autotools, CMake, pkg-config, a C compiler, and libusb** present first. On Windows this specifically means an MSYS2 + GNU-toolchain environment — the default MSVC toolchain can't build -an autotools stack. +an autotools stack — and libusb comes from vendored source too, since MSYS2 no +longer packages it for MINGW64. Everywhere you also need a [Rust toolchain](https://rustup.rs) (stable). @@ -82,7 +83,7 @@ The vendored C stack is autotools-based, so it builds under **MSYS2** with the pacman -S --needed base-devel git make autoconf automake libtool \ autoconf-archive gettext-devel pkgconf perl \ mingw-w64-x86_64-gcc mingw-w64-x86_64-pkgconf mingw-w64-x86_64-cmake \ - mingw-w64-x86_64-libusb mingw-w64-x86_64-nasm + mingw-w64-x86_64-nasm ``` 3. **Add the GNU Rust toolchain** (from PowerShell, or in the MINGW64 shell if From 2f23c6aacffbf2cdd5e849dd008e7ea0686445e4 Mon Sep 17 00:00:00 2001 From: "Frank Chiarulli Jr." Date: Tue, 17 Nov 2026 15:07:00 -0400 Subject: [PATCH 09/10] Fix idevicerestore's device waits on Windows libimobiledevice-glue implemented cond_t on Windows as a semaphore. A signal with no waiter was counted rather than dropped, so after one stray device event the next "wait for the device to disconnect" returned at once and idevicerestore failed the restore ("Device did not disconnect"). A wait also never re-took the mutex, so callers released it twice. Use a CONDITION_VARIABLE with the CRITICAL_SECTION mutex, which behaves like the pthreads version these callers are written for. Also give iBEC 60 seconds to boot in dfu_enter_recovery instead of 10, as the same step in idevicerestore.c already does. build.rs now applies patches// to any autotools library that has a patch directory, not just libirecovery. --- crates/restorekit-sys/build.rs | 23 +++--- crates/restorekit-sys/patches/README.md | 17 +++++ .../0009-wait-longer-for-ibec-to-boot.patch | 20 +++++ ...-real-condition-variables-on-windows.patch | 76 +++++++++++++++++++ 4 files changed, 125 insertions(+), 11 deletions(-) create mode 100644 crates/restorekit-sys/patches/idevicerestore/0009-wait-longer-for-ibec-to-boot.patch create mode 100644 crates/restorekit-sys/patches/libimobiledevice-glue/0001-real-condition-variables-on-windows.patch diff --git a/crates/restorekit-sys/build.rs b/crates/restorekit-sys/build.rs index b2d24e9..5ad64af 100644 --- a/crates/restorekit-sys/build.rs +++ b/crates/restorekit-sys/build.rs @@ -56,8 +56,8 @@ fn main() { ("libtatsu", "1.0.5"), ("libimobiledevice", "1.4.0"), ] { - let src = if lib == "libirecovery" { - patch_libirecovery_sources(&manifest, &vendor.join(lib), &out, &deps) + let src = if manifest.join("patches").join(lib).is_dir() { + patch_autotools_sources(&manifest, lib, &vendor.join(lib), &out, &deps) } else { vendor.join(lib) }; @@ -433,20 +433,21 @@ fn patch_idevicerestore_sources(manifest: &Path, vendor_src: &Path, out: &Path) root } -/// Copy libirecovery into OUT_DIR and apply `patches/libirecovery/` to it, for -/// the same reason as [`patch_idevicerestore_sources`]. libirecovery is built -/// with autotools, so it's only re-copied and rebuilt when the patches change. +/// Copy an autotools library into OUT_DIR and apply `patches//` to it, +/// for the same reason as [`patch_idevicerestore_sources`]. It's only re-copied +/// and rebuilt when the patches change. /// The stamp lives in the staging prefix next to build_autotools' marker, so a /// CI cache that restores only the prefix still skips the rebuild. -fn patch_libirecovery_sources( +fn patch_autotools_sources( manifest: &Path, + name: &str, vendor_src: &Path, out: &Path, deps: &Deps, ) -> PathBuf { use std::hash::{Hash, Hasher}; - let patch_dir = manifest.join("patches/libirecovery"); + let patch_dir = manifest.join("patches").join(name); println!("cargo:rerun-if-changed={}", patch_dir.display()); let mut patches: Vec = std::fs::read_dir(&patch_dir) .unwrap() @@ -462,9 +463,9 @@ fn patch_libirecovery_sources( } let stamp = format!("{:016x}", hasher.finish()); - let root = out.join("libirecovery-patched"); - let stamp_file = deps.prefix.join(".libirecovery-patches"); - let marker = deps.prefix.join(".built-libirecovery"); + let root = out.join(format!("{name}-patched")); + let stamp_file = deps.prefix.join(format!(".{name}-patches")); + let marker = deps.prefix.join(format!(".built-{name}")); if marker.exists() && std::fs::read_to_string(&stamp_file).is_ok_and(|s| s == stamp) { return root; } @@ -485,7 +486,7 @@ fn patch_libirecovery_sources( } // Force a fresh configure + build of the patched sources. let _ = std::fs::remove_file(&marker); - let _ = std::fs::remove_dir_all(deps.prefix.parent().unwrap().join("build/libirecovery")); + let _ = std::fs::remove_dir_all(deps.prefix.parent().unwrap().join("build").join(name)); std::fs::write(&stamp_file, stamp).unwrap(); root } diff --git a/crates/restorekit-sys/patches/README.md b/crates/restorekit-sys/patches/README.md index c58a6df..559ff5a 100644 --- a/crates/restorekit-sys/patches/README.md +++ b/crates/restorekit-sys/patches/README.md @@ -36,6 +36,23 @@ compiles the patched copy. 0x1332 ("failed to copy response for AppleTCON") while the restore carries on. When `ResponseTags` is missing, send the firmware like before, falling back to the ticket-only reply if it can't be extracted. +- `0009-wait-longer-for-ibec-to-boot.patch` — after iBEC is sent from DFU, + `dfu_enter_recovery` gave the Mac 10 seconds to drop off the bus and another + 10 to come back in recovery. An M4 mac mini whose earlier restore was cut + short took about 30 seconds to boot iBEC, so every retry failed with "Device + did not disconnect. Possibly invalid iBEC". Wait up to 60 seconds each, like + the same step in `idevicerestore.c` already does. + +## libimobiledevice-glue + +- `0001-real-condition-variables-on-windows.patch` — on Windows `cond_t` was a + semaphore: a signal with no waiter was counted instead of dropped, so a later + wait returned at once, and a wait never re-took the mutex, so callers then + released it twice. idevicerestore's device waits are written for pthreads, so + one stray device event made the next "wait for the device to disconnect" + return immediately and fail the restore. Use a `CONDITION_VARIABLE` with the + `CRITICAL_SECTION` mutex, which behaves like pthreads. Built with autotools + from a patched copy, like libirecovery. ## libirecovery diff --git a/crates/restorekit-sys/patches/idevicerestore/0009-wait-longer-for-ibec-to-boot.patch b/crates/restorekit-sys/patches/idevicerestore/0009-wait-longer-for-ibec-to-boot.patch new file mode 100644 index 0000000..60a5910 --- /dev/null +++ b/crates/restorekit-sys/patches/idevicerestore/0009-wait-longer-for-ibec-to-boot.patch @@ -0,0 +1,20 @@ +--- a/src/dfu.c ++++ b/src/dfu.c +@@ -671,7 +671,7 @@ int dfu_enter_recovery(struct idevicerestore_client_t* client, plist_t build_ide + } + + logger(LL_DEBUG, "Waiting for device to disconnect...\n"); +- cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 10000); ++ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 60000); + if (client->mode != MODE_UNKNOWN || (client->flags & FLAG_QUIT)) { + mutex_unlock(&client->device_event_mutex); + if (!(client->flags & FLAG_QUIT)) { +@@ -680,7 +680,7 @@ int dfu_enter_recovery(struct idevicerestore_client_t* client, plist_t build_ide + return -1; + } + logger(LL_DEBUG, "Waiting for device to reconnect in recovery mode...\n"); +- cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 10000); ++ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 60000); + if (client->mode != MODE_RECOVERY || (client->flags & FLAG_QUIT)) { + mutex_unlock(&client->device_event_mutex); + if (!(client->flags & FLAG_QUIT)) { diff --git a/crates/restorekit-sys/patches/libimobiledevice-glue/0001-real-condition-variables-on-windows.patch b/crates/restorekit-sys/patches/libimobiledevice-glue/0001-real-condition-variables-on-windows.patch new file mode 100644 index 0000000..28b0e8e --- /dev/null +++ b/crates/restorekit-sys/patches/libimobiledevice-glue/0001-real-condition-variables-on-windows.patch @@ -0,0 +1,76 @@ +--- a/src/thread.c ++++ b/src/thread.c +@@ -145,10 +145,14 @@ + #endif + } + ++/* On Windows cond_t is a CONDITION_VARIABLE (pointer-sized, like the `sem` ++ * handle the public header declares) used with the CRITICAL_SECTION mutex, so ++ * it behaves like pthreads: a signal with no waiter is dropped rather than ++ * counted, and a wait returns with the mutex held again. */ + void cond_init(cond_t* cond) + { + #ifdef _WIN32 +- cond->sem = CreateSemaphore(NULL, 0, 32767, NULL); ++ InitializeConditionVariable((PCONDITION_VARIABLE)cond); + #else + pthread_cond_init(cond, NULL); + #endif +@@ -157,7 +161,7 @@ + void cond_destroy(cond_t* cond) + { + #ifdef _WIN32 +- CloseHandle(cond->sem); ++ (void)cond; + #else + pthread_cond_destroy(cond); + #endif +@@ -166,11 +170,8 @@ + int cond_signal(cond_t* cond) + { + #ifdef _WIN32 +- int result = 0; +- if (!ReleaseSemaphore(cond->sem, 1, NULL)) { +- result = -1; +- } +- return result; ++ WakeConditionVariable((PCONDITION_VARIABLE)cond); ++ return 0; + #else + return pthread_cond_signal(cond); + #endif +@@ -179,14 +180,7 @@ + int cond_wait(cond_t* cond, mutex_t* mutex) + { + #ifdef _WIN32 +- mutex_unlock(mutex); +- DWORD res = WaitForSingleObject(cond->sem, INFINITE); +- switch (res) { +- case WAIT_OBJECT_0: +- return 0; +- default: +- return -1; +- } ++ return SleepConditionVariableCS((PCONDITION_VARIABLE)cond, (PCRITICAL_SECTION)mutex, INFINITE) ? 0 : -1; + #else + return pthread_cond_wait(cond, mutex); + #endif +@@ -195,15 +189,10 @@ + int cond_wait_timeout(cond_t* cond, mutex_t* mutex, unsigned int timeout_ms) + { + #ifdef _WIN32 +- mutex_unlock(mutex); +- DWORD res = WaitForSingleObject(cond->sem, timeout_ms); +- switch (res) { +- case WAIT_OBJECT_0: +- case WAIT_TIMEOUT: +- return 0; +- default: +- return -1; ++ if (SleepConditionVariableCS((PCONDITION_VARIABLE)cond, (PCRITICAL_SECTION)mutex, timeout_ms)) { ++ return 0; + } ++ return GetLastError() == ERROR_TIMEOUT ? 0 : -1; + #else + struct timespec ts; + struct timeval now; From f07fce0726186dcafce57c4d79f2063af59cc6bb Mon Sep 17 00:00:00 2001 From: "Frank Chiarulli Jr." Date: Tue, 17 Nov 2026 15:07:00 -0400 Subject: [PATCH 10/10] Bind Windows' own WinUSB instead of a self-signed driver package setup-driver generated a WinUSB INF, signed its catalog with a self-signed certificate it added to the machine's trusted roots, and staged it with pnputil. Windows on ARM refuses such packages outright, since Code Integrity only loads Microsoft-signed drivers. Bind the inbox winusb.inf instead: build a driver list from just that INF with DI_FLAGSEX_ALLOWEXCLUDEDDRVS (its "WinUsb Device" entry matches USB\MS_COMP_WINUSB, not the Mac, as Device Manager's "Have Disk" route allows), install it on the one device instance with DiInstallDevice, and write the mode's DeviceInterfaceGUIDs to the device's registry key the way the INF's AddReg did. A device already on WinUSB without a GUID (a dongle on old firmware) just gets the GUID and a restart. The restore-mode watcher is now a Rust loop doing the same for the restore-mode interface, and for any DFU, recovery or KIS device left without a driver. No certificate, catalog, pnputil or PowerShell, and it works the same on x64 and ARM64, so the ARM-only restore check is gone. --- crates/restorekit/src/driver.rs | 986 +++++++++++++++---------------- crates/restorekit/src/restore.rs | 5 - docs/windows-restore.md | 70 ++- 3 files changed, 526 insertions(+), 535 deletions(-) diff --git a/crates/restorekit/src/driver.rs b/crates/restorekit/src/driver.rs index eda6ec6..2ad8123 100644 --- a/crates/restorekit/src/driver.rs +++ b/crates/restorekit/src/driver.rs @@ -1,22 +1,19 @@ -//! WinUSB driver setup for Apple DFU/recovery devices (Windows only). +//! WinUSB setup for Apple DFU/recovery/restore devices and RecoverKit dongles +//! (Windows only). //! -//! On Windows, libusb (and `nusb`) can only *open* a device that has a -//! libusb-class driver bound to it. A Mac in DFU/recovery enumerates under -//! Apple's vendor id but Windows binds no usable driver, so restorekit can't -//! talk to it until **WinUSB** is bound. (Detection still works without a -//! driver — that's plain enumeration — only the restore needs WinUSB.) +//! On Windows, libusb (and `nusb`) can only *open* a device that has WinUSB +//! bound to it and a device interface GUID registered for it. Apple's own +//! drivers (Windows Update installs them on first plug-in) serve DFU, recovery +//! and KIS directly through libirecovery, but not restore mode, where Apple's +//! WinUSB variant can't be opened by libusb; and a machine without them has no +//! driver for those modes at all. //! -//! Windows won't install a driver package from an unsigned INF, so we do what -//! Zadig/libwdi do: generate a self-signed code-signing certificate, build and -//! sign a catalog for a WinUSB INF, trust the certificate, then bind the driver -//! with `pnputil`. That whole dance is scripted through PowerShell (present on -//! every supported Windows) rather than reimplementing the crypto here. -//! -//! Installing a driver and trusting a certificate need administrator rights; -//! the caller (the CLI's `setup-driver` command) elevates first. - -use std::io::Write; -use std::process::Command; +//! Rather than shipping a driver package (which Windows only loads when signed, +//! and on ARM only when Microsoft signed it), restorekit binds Windows' own +//! `winusb.inf` "WinUsb Device" driver to the device instance, the way Device +//! Manager's "Have Disk / show all devices" route does, and writes the +//! interface GUID into the device's registry key the way an INF's `AddReg` +//! would. Both need administrator rights; the callers elevate first. use restorekit_dongle_proto as proto; @@ -32,8 +29,7 @@ pub const APPLE_VID: u16 = 0x05ac; /// Deliberately NOT Apple's normal-mode range (0x129x): on Windows, binding /// WinUSB *replaces* a device's driver, so covering normal mode would hijack a /// plugged-in iPhone/iPad from Apple's own driver. Every id here is only ever an -/// Apple device in recovery/DFU, never a normal one — so staging them all up -/// front is safe and lets a restore hop DFU -> recovery without a re-run. +/// Apple device in recovery/DFU, never a normal one. pub const DRIVER_PIDS: &[u16] = &[ 0x1222, // WTF 0x1227, // DFU @@ -44,52 +40,24 @@ pub const DRIVER_PIDS: &[u16] = &[ /// Apple's normal-mode product-id range (0x1290–0x12af). A Mac in **restore /// mode** enumerates as a composite device with one of these ids plus a -/// `RESTORE_MODE` qualifier; we bind WinUSB to that qualified interface only (see -/// [`winusb_inf`]), never the bare id — so a normal iPhone/iPad is untouched. +/// `RESTORE_MODE` qualifier; we bind WinUSB to that qualified interface only, +/// never the bare id, so a normal iPhone/iPad is untouched. const RESTORE_MODE_PIDS: std::ops::RangeInclusive = 0x1290..=0x12af; +/// Device interface GUIDs, per mode. The DFU, recovery, port DFU and KIS ones +/// are what Apple's drivers register, which libirecovery's Windows backend +/// enumerates; the restore-mode one is ours, for libusb. +const GUID_DFU: &str = "{B8085869-FEB9-404B-8CB1-1E5C14FA8C54}"; +const GUID_IBOOT: &str = "{ED82A167-D61A-4AF6-9AB6-11E52236C576}"; +const GUID_PORTDFU: &str = "{AF633FF1-1170-4CA6-AE9E-08D001421EAA}"; +const GUID_KIS: &str = "{B36F4137-F4EF-4BFC-A25A-C2410768EE37}"; +const GUID_RESTORE: &str = "{3F966BD9-FA04-4EC5-991C-D326973B5128}"; + /// Does `pid` name a mode restorekit binds WinUSB for? pub fn is_target_pid(pid: u16) -> bool { DRIVER_PIDS.contains(&pid) } -/// What to tell Windows on ARM users, where restorekit's own driver package -/// can't be installed. -pub const ARM64_HINT: &str = "Windows on ARM only loads Microsoft-signed driver packages, so \ - restorekit can't install its own USB driver here. Install Apple Devices from the Microsoft \ - Store (or iTunes) instead and retry: restorekit then uses Apple's drivers and Apple Mobile \ - Device Service, and needs no driver of its own"; - -/// Whether Windows itself runs on ARM64, including when this x64 build runs -/// under emulation there. -#[cfg(target_os = "windows")] -pub fn native_arm64() -> bool { - use windows_sys::Win32::System::SystemInformation::IMAGE_FILE_MACHINE_ARM64; - use windows_sys::Win32::System::Threading::{GetCurrentProcess, IsWow64Process2}; - let (mut process, mut native) = (0u16, 0u16); - let ok = unsafe { IsWow64Process2(GetCurrentProcess(), &mut process, &mut native) != 0 }; - ok && native == IMAGE_FILE_MACHINE_ARM64 -} - -/// Whether our WinUSB package is in the driver store (the restore-mode watcher -/// binds the newest one). -#[cfg(target_os = "windows")] -pub fn winusb_package_staged() -> bool { - let Some(windir) = std::env::var_os("windir") else { - return false; - }; - let Ok(entries) = std::fs::read_dir(std::path::Path::new(&windir).join("INF")) else { - return false; - }; - entries.flatten().any(|e| { - let name = e.file_name().to_string_lossy().to_ascii_lowercase(); - name.starts_with("oem") - && name.ends_with(".inf") - && std::fs::read_to_string(e.path()) - .is_ok_and(|c| c.contains("RestoreKit") && c.contains("RESTORE_MODE")) - }) -} - /// A connected Apple device that needs WinUSB bound before restorekit can use it. #[derive(Debug, Clone)] pub struct Target { @@ -110,14 +78,6 @@ pub fn connected_targets() -> Result> { .collect()) } -/// How many RecoverKit dongles are connected (by their vendor interface). -fn connected_dongles() -> Result { - Ok(present_instance_ids()? - .iter() - .filter(|id| is_dongle_interface(id)) - .count()) -} - /// The PnP hardware id of a dongle's vendor interface. fn dongle_interface_hwid() -> String { format!( @@ -198,15 +158,46 @@ fn target_pid_from_instance_id(instance_id: &str) -> Option { is_target_pid(pid).then_some(pid) } -/// Bind the WinUSB driver to every connected Apple DFU/recovery/restore device -/// and RecoverKit dongle, so libusb and nusb can open them. Returns the number -/// of devices set up. +/// The interface GUID restorekit binds `instance_id` with, if it's a device +/// restorekit drives: a DFU-family or recovery device itself (not one of its +/// interfaces), a restore-mode data interface, or a dongle's vendor interface. +fn bind_guid(instance_id: &str) -> Option<&'static str> { + if is_dongle_interface(instance_id) { + return Some(proto::WINUSB_INTERFACE_GUID); + } + let upper = instance_id.to_ascii_uppercase(); + let rest = upper.strip_prefix(&format!("USB\\VID_{APPLE_VID:04X}&PID_"))?; + let pid = u16::from_str_radix(rest.get(..4)?, 16).ok()?; + let qualifier = rest.get(4..)?; + if qualifier.starts_with("&RESTORE_MODE&MI_00\\") { + return RESTORE_MODE_PIDS.contains(&pid).then_some(GUID_RESTORE); + } + if !qualifier.starts_with('\\') { + return None; + } + match pid { + 0x1222 | 0x1227 => Some(GUID_DFU), + 0x1280..=0x1283 => Some(GUID_IBOOT), + 0xf014 => Some(GUID_PORTDFU), + 0x1881 => Some(GUID_KIS), + _ => None, + } +} + +/// Make every connected Apple DFU/recovery device and RecoverKit dongle +/// reachable, binding WinUSB where needed. Devices on Apple's own drivers are +/// left alone: libirecovery talks to those directly, and moving a KIS Mac off +/// AppleKIS strands it until it re-enters DFU. Returns the number of devices +/// set up. /// /// Must run elevated (the CLI handles that). pub fn install_winusb(progress: ProgressFn) -> Result { - let targets = connected_targets()?; - let dongles = connected_dongles()?; - if targets.is_empty() && dongles == 0 { + let devices: Vec<(String, &str)> = present_instance_ids()? + .into_iter() + .filter_map(|id| bind_guid(&id).map(|g| (id, g))) + .filter(|(id, _)| !id.to_ascii_uppercase().contains("&RESTORE_MODE&")) + .collect(); + if devices.is_empty() { return Err(Error::DriverInstall( "no Apple device in DFU or recovery mode and no RecoverKit dongle is connected — \ plug in the dongle or put the target into DFU (see `restorekit status`) and re-run" @@ -215,342 +206,353 @@ pub fn install_winusb(progress: ProgressFn) -> Result { } progress(Event::DriverSetupStarting); - run_setup_script(false).map_err(|e| match e { - Error::DriverInstall(detail) if native_arm64() => { - Error::DriverInstall(format!("{ARM64_HINT}\n\n{detail}")) + let mut failures = Vec::new(); + for (id, guid) in &devices { + let dongle = is_dongle_interface(id); + let result = if !dongle && winusb::driver_of(id).is_some_and(|d| d.is_apple()) { + Ok(()) + } else { + winusb::bind(id, guid) + }; + match result { + Ok(()) => progress(Event::DriverBound { + name: if dongle { + "RecoverKit dongle".into() + } else { + target_pid_from_instance_id(id) + .map(|pid| format!("Apple device (mode {pid:#06x})")) + .unwrap_or_else(|| id.clone()) + }, + }), + Err(e) => failures.push(format!("{id}: {e}")), } - e => e, - })?; - - for t in &targets { - progress(Event::DriverBound { - name: t.name.clone(), - }); - } - for _ in 0..dongles { - progress(Event::DriverBound { - name: "RecoverKit dongle".into(), - }); - } - Ok(targets.len() + dongles) -} - -/// Sign and stage our WinUSB package, then (unless `stage_only`) force it onto -/// every connected device it covers. Must run elevated. -fn run_setup_script(stage_only: bool) -> Result<()> { - // A private work dir holding only the INF(s) — the catalog hashes this - // directory, so nothing else may live in it. The script goes alongside. - let base = std::env::temp_dir(); - let stamp = std::process::id(); - let work = base.join(format!("restorekit-winusb-{stamp}")); - let script = base.join(format!("restorekit-winusb-{stamp}.ps1")); - let _ = std::fs::remove_dir_all(&work); - std::fs::create_dir_all(&work).map_err(|e| Error::DriverInstall(e.to_string()))?; - - // One INF covering every DFU/recovery mode, staged in a single pnputil run, - // so a restore that hops DFU -> recovery is covered without re-running. - let inf_path = work.join("restorekit_winusb.inf"); - write_file(&inf_path, winusb_inf(DRIVER_PIDS).as_bytes())?; - write_file(&script, WINUSB_SETUP_PS1.as_bytes())?; - - // CREATE_NO_WINDOW: don't flash a PowerShell console (matters for the GUI). - use std::os::windows::process::CommandExt; - const CREATE_NO_WINDOW: u32 = 0x0800_0000; - let mut cmd = Command::new("powershell"); - cmd.creation_flags(CREATE_NO_WINDOW) - .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"]) - .arg(&script) - .arg("-WorkDir") - .arg(&work) - .arg("-DeviceRegex") - .arg(bind_regex()); - if stage_only { - cmd.arg("-StageOnly"); } - let output = cmd - .output() - .map_err(|e| Error::DriverInstall(format!("failed to run PowerShell: {e}"))); - - let _ = std::fs::remove_dir_all(&work); - let _ = std::fs::remove_file(&script); - - let output = output?; - if !output.status.success() { - // pnputil's own output (on stdout) usually says why; keep both. - let detail = [&output.stderr, &output.stdout] - .iter() - .map(|b| String::from_utf8_lossy(b).trim().to_string()) - .filter(|s| !s.is_empty()) - .collect::>() - .join("\n"); + if !failures.is_empty() { return Err(Error::DriverInstall(format!( - "WinUSB setup did not complete: {detail}" + "WinUSB setup did not complete: {}", + failures.join("; ") ))); } - Ok(()) + Ok(devices.len()) } -/// PowerShell regex matching the instance ids the setup script binds: the -/// Apple modes in [`DRIVER_PIDS`] and the dongle's vendor interface. -fn bind_regex() -> String { - let pids: Vec = DRIVER_PIDS.iter().map(|p| format!("{p:04X}")).collect(); - format!( - "^USB\\\\VID_{APPLE_VID:04X}&PID_({})\\\\|^{}\\\\", - pids.join("|"), - dongle_interface_hwid().replace('\\', "\\\\") - ) -} - -/// A WinUSB device INF binding the inbox `winusb.sys` to every Apple product id -/// in `pids`. -/// -/// Uses the documented `Include=winusb.inf` / `Needs=WINUSB.NT` form, which -/// relies on the in-box WinUSB driver (Windows 10+), so no redistributable -/// driver binaries ship with restorekit. `CatalogFile` names the signed catalog -/// the setup script produces. -fn winusb_inf(pids: &[u16]) -> String { - let mut models = String::new(); - for pid in pids { - let install = match *pid { - 0x1222 | 0x1227 => "WINUSB_DFU_Install", - 0x1280..=0x1283 => "WINUSB_IBOOT_Install", - 0xf014 => "WINUSB_PORTDFU_Install", - 0x1881 => "WINUSB_KIS_Install", - _ => unreachable!("unsupported Apple mode PID"), - }; - models.push_str(&format!( - "%DeviceName% = {install}, USB\\VID_{APPLE_VID:04X}&PID_{pid:04X}\n" - )); - } - // Restore mode (Apple Silicon): the device becomes a USB *composite* whose - // data interface enumerates as `VID&PID&RESTORE_MODE&MI_00`. Apple's - // `appleusb.inf` binds a WinUSB *variant* that libusb can't open - // (`winusbx_open` → ERROR_NOT_SUPPORTED), so bind our plain `winusb.sys` - // there too — a more specific, trusted match that wins on re-enumeration. - // The `RESTORE_MODE` qualifier is restore-only, so this never hijacks a - // normal-mode iPhone/iPad sharing a 0x129x product id. - for pid in RESTORE_MODE_PIDS { - models.push_str(&format!( - "%DeviceName% = WINUSB_RESTORE_Install, USB\\VID_{APPLE_VID:04X}&PID_{pid:04X}&RESTORE_MODE&MI_00\n" - )); - } - // The dongle's vendor interface. Its firmware asks Windows for WinUSB but, - // through 0.1.3, gave no interface GUID, without which Windows never exposes - // that interface to apps; binding it here supplies the GUID. More specific - // than the generic WinUSB compatible-id match, so it wins that ranking. - models.push_str(&format!( - "%DongleName% = WINUSB_DONGLE_Install, {}\n", - dongle_interface_hwid() - )); - format!( - r#"; Generated by RestoreKit - binds WinUSB to an Apple device so libusb can access it. -[Version] -Signature = "$Windows NT$" -Class = USBDevice -ClassGuid = {{88BAE032-5A81-49f0-BC3D-A4FF138216D6}} -Provider = %ProviderName% -CatalogFile = restorekit_winusb.cat -DriverVer = 01/01/2024,1.0.0.2 - -[Manufacturer] -%ProviderName% = Standard,NTamd64,NTarm64 - -[Standard.NTamd64] -{models} -[Standard.NTarm64] -{models} -[WINUSB_DFU_Install.NT] -Include = winusb.inf -Needs = WINUSB.NT - -[WINUSB_DFU_Install.NT.Services] -Include = winusb.inf -Needs = WINUSB.NT.Services - -[WINUSB_DFU_Install.NT.HW] -AddReg = WINUSB_DFU_AddReg - -[WINUSB_DFU_AddReg] -HKR,,DeviceInterfaceGUIDs,0x10000,"{{B8085869-FEB9-404B-8CB1-1E5C14FA8C54}}" - -[WINUSB_IBOOT_Install.NT] -Include = winusb.inf -Needs = WINUSB.NT - -[WINUSB_IBOOT_Install.NT.Services] -Include = winusb.inf -Needs = WINUSB.NT.Services +/// Binding Windows' own WinUSB to one device instance. +mod winusb { + use std::os::windows::ffi::OsStrExt; + use std::ptr::{null, null_mut}; -[WINUSB_IBOOT_Install.NT.HW] -AddReg = WINUSB_IBOOT_AddReg + use windows_sys::Win32::Devices::DeviceAndDriverInstallation::{ + DiInstallDevice, SetupDiBuildDriverInfoList, SetupDiCallClassInstaller, + SetupDiCreateDevRegKeyW, SetupDiCreateDeviceInfoList, SetupDiDestroyDeviceInfoList, + SetupDiEnumDriverInfoW, SetupDiGetDeviceInstallParamsW, SetupDiGetDriverInfoDetailW, + SetupDiOpenDevRegKey, SetupDiOpenDeviceInfoW, SetupDiSetClassInstallParamsW, + SetupDiSetDeviceInstallParamsW, DICS_FLAG_GLOBAL, DICS_PROPCHANGE, DIF_PROPERTYCHANGE, + DIREG_DEV, DIREG_DRV, DI_ENUMSINGLEINF, DI_FLAGSEX_ALLOWEXCLUDEDDRVS, HDEVINFO, + SPDIT_CLASSDRIVER, SP_CLASSINSTALL_HEADER, SP_DEVINFO_DATA, SP_DEVINSTALL_PARAMS_W, + SP_DRVINFO_DATA_V2_W, SP_DRVINFO_DETAIL_DATA_W, SP_PROPCHANGE_PARAMS, + }; + use windows_sys::Win32::Foundation::{GetLastError, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Registry::{ + RegCloseKey, RegQueryValueExW, RegSetValueExW, HKEY, KEY_READ, REG_MULTI_SZ, + }; + use windows_sys::Win32::System::SystemInformation::GetWindowsDirectoryW; -[WINUSB_IBOOT_AddReg] -HKR,,DeviceInterfaceGUIDs,0x10000,"{{ED82A167-D61A-4AF6-9AB6-11E52236C576}}" + use crate::error::{Error, Result}; -[WINUSB_PORTDFU_Install.NT] -Include = winusb.inf -Needs = WINUSB.NT + /// `{88BAE032-5A81-49F0-BC3D-A4FF138216D6}`, the USBDevice setup class of + /// `winusb.inf`. + const USBDEVICE_CLASS: windows_sys::core::GUID = + windows_sys::core::GUID::from_u128(0x88bae032_5a81_49f0_bc3d_a4ff138216d6); + const WINUSB_HWID: &str = "USB\\MS_COMP_WINUSB"; -[WINUSB_PORTDFU_Install.NT.Services] -Include = winusb.inf -Needs = WINUSB.NT.Services + fn wide(s: &str) -> Vec { + std::ffi::OsStr::new(s).encode_wide().chain([0]).collect() + } -[WINUSB_PORTDFU_Install.NT.HW] -AddReg = WINUSB_PORTDFU_AddReg + fn err(what: &str) -> Error { + Error::DriverInstall(format!("{what} failed: {:#x}", unsafe { GetLastError() })) + } -[WINUSB_PORTDFU_AddReg] -HKR,,DeviceInterfaceGUIDs,0x10000,"{{AF633FF1-1170-4CA6-AE9E-08D001421EAA}}" + /// The driver currently installed on a device. + pub(super) struct Driver { + inf: String, + provider: String, + } -[WINUSB_KIS_Install.NT] -Include = winusb.inf -Needs = WINUSB.NT + impl Driver { + pub(super) fn is_apple(&self) -> bool { + self.provider.starts_with("Apple") + } -[WINUSB_KIS_Install.NT.Services] -Include = winusb.inf -Needs = WINUSB.NT.Services + /// Plain WinUSB: Windows' own `winusb.inf`, or an older restorekit's + /// package. (Apple's restore-mode driver is WinUSB too, but a variant + /// libusb can't open.) + fn is_plain_winusb(&self) -> bool { + self.inf.eq_ignore_ascii_case("winusb.inf") || self.provider == "RestoreKit" + } + } -[WINUSB_KIS_Install.NT.HW] -AddReg = WINUSB_KIS_AddReg + /// An open device-info set holding one device. + struct Device { + set: HDEVINFO, + data: SP_DEVINFO_DATA, + } -[WINUSB_KIS_AddReg] -HKR,,DeviceInterfaceGUIDs,0x10000,"{{B36F4137-F4EF-4BFC-A25A-C2410768EE37}}" + impl Drop for Device { + fn drop(&mut self) { + unsafe { SetupDiDestroyDeviceInfoList(self.set) }; + } + } -[WINUSB_RESTORE_Install.NT] -Include = winusb.inf -Needs = WINUSB.NT + impl Device { + fn open(instance_id: &str) -> Result { + unsafe { + let set = SetupDiCreateDeviceInfoList(null(), null_mut()); + if set == INVALID_HANDLE_VALUE as HDEVINFO { + return Err(err("SetupDiCreateDeviceInfoList")); + } + let mut dev = Device { + set, + data: SP_DEVINFO_DATA { + cbSize: std::mem::size_of::() as u32, + ..Default::default() + }, + }; + if SetupDiOpenDeviceInfoW( + set, + wide(instance_id).as_ptr(), + null_mut(), + 0, + &mut dev.data, + ) == 0 + { + return Err(err("SetupDiOpenDeviceInfo")); + } + Ok(dev) + } + } -[WINUSB_RESTORE_Install.NT.Services] -Include = winusb.inf -Needs = WINUSB.NT.Services + fn reg_key(&self, which: u32) -> Option { + let key = unsafe { + SetupDiOpenDevRegKey(self.set, &self.data, DICS_FLAG_GLOBAL, 0, which, KEY_READ) + }; + (key != INVALID_HANDLE_VALUE as HKEY).then_some(key) + } -[WINUSB_RESTORE_Install.NT.HW] -AddReg = WINUSB_RESTORE_AddReg + fn driver(&self) -> Option { + let key = self.reg_key(DIREG_DRV)?; + let inf = read_string(key, "InfPath"); + let provider = read_string(key, "ProviderName"); + unsafe { RegCloseKey(key) }; + Some(Driver { + inf: inf.unwrap_or_default(), + provider: provider.unwrap_or_default(), + }) + } -[WINUSB_RESTORE_AddReg] -HKR,,DeviceInterfaceGUIDs,0x10000,"{{3F966BD9-FA04-4EC5-991C-D326973B5128}}" + fn interface_guids(&self) -> Option { + let key = self.reg_key(DIREG_DEV)?; + let guids = read_string(key, "DeviceInterfaceGUIDs"); + unsafe { RegCloseKey(key) }; + guids + } -[WINUSB_DONGLE_Install.NT] -Include = winusb.inf -Needs = WINUSB.NT + fn set_interface_guid(&self, guid: &str) -> Result<()> { + unsafe { + let key = SetupDiCreateDevRegKeyW( + self.set, + &self.data, + DICS_FLAG_GLOBAL, + 0, + DIREG_DEV, + null_mut(), + null(), + ); + if key == INVALID_HANDLE_VALUE as HKEY { + return Err(err("opening the device's registry key")); + } + // REG_MULTI_SZ: the string, its NUL, and the list's closing NUL. + let mut value = wide(guid); + value.push(0); + let rc = RegSetValueExW( + key, + wide("DeviceInterfaceGUIDs").as_ptr(), + 0, + REG_MULTI_SZ, + value.as_ptr().cast(), + (value.len() * 2) as u32, + ); + RegCloseKey(key); + if rc != 0 { + return Err(Error::DriverInstall(format!( + "writing DeviceInterfaceGUIDs failed: {rc:#x}" + ))); + } + Ok(()) + } + } -[WINUSB_DONGLE_Install.NT.Services] -Include = winusb.inf -Needs = WINUSB.NT.Services + /// Restart the device so its driver re-reads its settings. + fn restart(&self) -> Result<()> { + unsafe { + let params = SP_PROPCHANGE_PARAMS { + ClassInstallHeader: SP_CLASSINSTALL_HEADER { + cbSize: std::mem::size_of::() as u32, + InstallFunction: DIF_PROPERTYCHANGE, + }, + StateChange: DICS_PROPCHANGE, + Scope: DICS_FLAG_GLOBAL, + HwProfile: 0, + }; + if SetupDiSetClassInstallParamsW( + self.set, + &self.data, + ¶ms.ClassInstallHeader, + std::mem::size_of::() as u32, + ) == 0 + || SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, self.set, &self.data) == 0 + { + return Err(err("restarting the device")); + } + Ok(()) + } + } -[WINUSB_DONGLE_Install.NT.HW] -AddReg = WINUSB_DONGLE_AddReg + /// Install `winusb.inf`'s "WinUsb Device" on this device. Its hardware + /// id (`USB\MS_COMP_WINUSB`) doesn't match the device, so allow + /// non-matching drivers and offer only that one INF. + fn install_winusb(&mut self) -> Result<()> { + unsafe { + let mut params = SP_DEVINSTALL_PARAMS_W { + cbSize: std::mem::size_of::() as u32, + ..std::mem::zeroed() + }; + if SetupDiGetDeviceInstallParamsW(self.set, &self.data, &mut params) == 0 { + return Err(err("SetupDiGetDeviceInstallParams")); + } + let n = GetWindowsDirectoryW(params.DriverPath.as_mut_ptr(), 200) as usize; + if n == 0 || n >= 200 { + return Err(err("GetWindowsDirectory")); + } + for (i, c) in "\\INF\\winusb.inf".encode_utf16().chain([0]).enumerate() { + params.DriverPath[n + i] = c; + } + params.Flags |= DI_ENUMSINGLEINF; + params.FlagsEx |= DI_FLAGSEX_ALLOWEXCLUDEDDRVS; + if SetupDiSetDeviceInstallParamsW(self.set, &self.data, ¶ms) == 0 { + return Err(err("SetupDiSetDeviceInstallParams")); + } + self.data.ClassGuid = USBDEVICE_CLASS; + if SetupDiBuildDriverInfoList(self.set, &mut self.data, SPDIT_CLASSDRIVER) == 0 { + return Err(err("SetupDiBuildDriverInfoList")); + } + let mut node = SP_DRVINFO_DATA_V2_W { + cbSize: std::mem::size_of::() as u32, + ..std::mem::zeroed() + }; + let mut found = false; + let mut index = 0; + while SetupDiEnumDriverInfoW( + self.set, + &self.data, + SPDIT_CLASSDRIVER, + index, + &mut node, + ) != 0 + { + index += 1; + // The detail struct ends in a variable-length hardware id. + let mut buf = [0u64; 512]; + let detail = buf.as_mut_ptr().cast::(); + (*detail).cbSize = std::mem::size_of::() as u32; + if SetupDiGetDriverInfoDetailW( + self.set, + &self.data, + &node, + detail, + std::mem::size_of_val(&buf) as u32, + null_mut(), + ) == 0 + { + continue; + } + let hwid = (*detail).HardwareID.as_ptr(); + let len = (0..).take_while(|&i| *hwid.add(i) != 0).count(); + let hwid = String::from_utf16_lossy(std::slice::from_raw_parts(hwid, len)); + if hwid.eq_ignore_ascii_case(WINUSB_HWID) { + found = true; + break; + } + } + if !found { + return Err(Error::DriverInstall( + "Windows' winusb.inf has no WinUsb Device entry".into(), + )); + } + let mut reboot = 0; + if DiInstallDevice(null_mut(), self.set, &self.data, &node, 0, &mut reboot) == 0 { + return Err(err("installing WinUSB")); + } + Ok(()) + } + } + } -[WINUSB_DONGLE_AddReg] -HKR,,DeviceInterfaceGUIDs,0x10000,"{dongle_guid}" + fn read_string(key: HKEY, name: &str) -> Option { + let name = wide(name); + let mut buf = [0u16; 512]; + let mut size = std::mem::size_of_val(&buf) as u32; + let rc = unsafe { + RegQueryValueExW( + key, + name.as_ptr(), + null(), + null_mut(), + buf.as_mut_ptr().cast(), + &mut size, + ) + }; + if rc != 0 { + return None; + } + let chars = &buf[..(size as usize / 2).min(buf.len())]; + let end = chars.iter().position(|&c| c == 0).unwrap_or(chars.len()); + Some(String::from_utf16_lossy(&chars[..end])) + } -[Strings] -ProviderName = "RestoreKit" -DeviceName = "Apple Mobile Device (RestoreKit WinUSB)" -DongleName = "RecoverKit Dongle (RestoreKit WinUSB)" -"#, - dongle_guid = proto::WINUSB_INTERFACE_GUID - ) -} + /// The driver installed on `instance_id`, if any. + pub(super) fn driver_of(instance_id: &str) -> Option { + Device::open(instance_id).ok()?.driver() + } -/// PowerShell that signs and installs the WinUSB package for `$WorkDir`. -/// -/// Reuses a stable `CN=RestoreKit WinUSB` code-signing cert (creating it once), -/// builds + signs a catalog over the INF(s), trusts the cert and stages the -/// package. Unless `-StageOnly`, it then forces the package onto every present -/// device matching `-DeviceRegex` and verifies WinUSB attached, exiting -/// non-zero if not. -/// -/// Forcing is needed because Windows Update installs Apple's own WHQL-signed -/// drivers (e.g. `applekis.inf` for 05ac:1881), which outrank our self-signed -/// package, so a plain `pnputil /install` leaves them in place. -const WINUSB_SETUP_PS1: &str = r#"param( - [Parameter(Mandatory=$true)][string]$WorkDir, - [string]$DeviceRegex = '^$', - [switch]$StageOnly -) -$ErrorActionPreference = 'Stop' -$cat = Join-Path $WorkDir 'restorekit_winusb.cat' -$subject = 'CN=RestoreKit WinUSB' -$cert = Get-ChildItem Cert:\CurrentUser\My -ErrorAction SilentlyContinue | - Where-Object { $_.Subject -eq $subject } | Select-Object -First 1 -if (-not $cert) { - $cert = New-SelfSignedCertificate -Type CodeSigningCert -Subject $subject ` - -CertStoreLocation Cert:\CurrentUser\My -KeyUsage DigitalSignature ` - -TextExtension @('2.5.29.37={text}1.3.6.1.5.5.7.3.3') -} -New-FileCatalog -Path $WorkDir -CatalogFilePath $cat -CatalogVersion 2 | Out-Null -Set-AuthenticodeSignature -FilePath $cat -Certificate $cert | Out-Null -# Trust the cert machine-wide through X509Store: current Windows 11 refuses -# Import-Certificate into LocalMachine\TrustedPublisher, even elevated. -$pub = [Security.Cryptography.X509Certificates.X509Certificate2]::new($cert.RawData) -foreach ($name in 'Root', 'TrustedPublisher') { - $store = [Security.Cryptography.X509Certificates.X509Store]::new($name, 'LocalMachine') - $store.Open('ReadWrite') - $store.Add($pub) - $store.Close() -} -$infFile = Get-ChildItem $WorkDir -Filter '*.inf' | Select-Object -First 1 -$log = pnputil /add-driver $infFile.FullName /install | Out-String -Write-Output $log -if ($log -match 'Failed to add driver package') { - Write-Error "pnputil could not stage the driver package" - exit 1 -} -# The staged copy (oemNN.inf) pnputil just published. -$leaf = if ($log -match 'Published Name:\s+(oem\d+\.inf)') { $Matches[1] } else { $null } -if (-not $leaf) { - Write-Error 'pnputil did not report a published driver package' - exit 1 -} -if ($StageOnly) { exit 0 } - -Add-Type @" -using System; -using System.Runtime.InteropServices; -public static class RkNewDev { - [DllImport("newdev.dll", CharSet=CharSet.Unicode, SetLastError=true)] - public static extern bool UpdateDriverForPlugAndPlayDevices( - IntPtr hwnd, string HardwareId, string FullInfPath, uint InstallFlags, out bool bReboot); -} -"@ -$staged = Join-Path $env:windir "INF\$leaf" -$devices = Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | - Where-Object { $_.InstanceId -match $DeviceRegex } -# Apple's own drivers (Windows Update, iTunes, Apple Devices) already work with -# restorekit, and moving a KIS Mac off AppleKIS strands it until it re-enters -# DFU, so only bind devices on no driver or someone else's. -function Test-AppleDriver($id) { - $provider = (Get-PnpDeviceProperty -InstanceId $id -KeyName DEVPKEY_Device_DriverProvider -ErrorAction SilentlyContinue).Data - return ($provider -match '^Apple') -} -foreach ($dev in $devices) { - $infNow = (Get-PnpDeviceProperty -InstanceId $dev.InstanceId -KeyName DEVPKEY_Device_DriverInfPath -ErrorAction SilentlyContinue).Data - if ($infNow -eq $leaf) { continue } - if (Test-AppleDriver $dev.InstanceId) { continue } - # INSTALLFLAG_FORCE (0x1) | INSTALLFLAG_NONINTERACTIVE (0x4). - $hwid = $dev.InstanceId -replace '\\[^\\]+$', '' - $reboot = $false - if (-not [RkNewDev]::UpdateDriverForPlugAndPlayDevices([IntPtr]::Zero, $hwid, $staged, 0x5, [ref]$reboot)) { - $code = [Runtime.InteropServices.Marshal]::GetLastWin32Error() - Write-Output ("could not bind {0} (was {1}): error 0x{2:X8}" -f $dev.InstanceId, $infNow, $code) + /// Whether `instance_id` already has plain WinUSB with `guid` registered. + pub(super) fn is_bound(instance_id: &str, guid: &str) -> bool { + Device::open(instance_id).is_ok_and(|d| { + d.driver().is_some_and(|drv| drv.is_plain_winusb()) + && d.interface_guids() + .is_some_and(|g| g.eq_ignore_ascii_case(guid)) + }) } -} -$ready = Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | - Where-Object { $_.InstanceId -match $DeviceRegex } | - Where-Object { - (Test-AppleDriver $_.InstanceId) -or - (Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName 'DEVPKEY_Device_Service' -ErrorAction SilentlyContinue).Data -eq 'WINUSB' + + /// Give `instance_id` plain WinUSB with `guid` as its interface GUID: + /// write the GUID, then install Windows' WinUSB, or restart the device if + /// it already has it so WinUSB registers the GUID. + pub(super) fn bind(instance_id: &str, guid: &str) -> Result<()> { + let mut dev = Device::open(instance_id)?; + let plain = dev.driver().is_some_and(|d| d.is_plain_winusb()); + let has_guid = dev + .interface_guids() + .is_some_and(|g| g.eq_ignore_ascii_case(guid)); + if plain && has_guid { + return Ok(()); + } + dev.set_interface_guid(guid)?; + if plain { + dev.restart() + } else { + dev.install_winusb() + } } -if ($ready) { exit 0 } -Write-Error 'WinUSB was not bound to any connected device' -exit 1 -"#; - -fn write_file(path: &std::path::Path, bytes: &[u8]) -> Result<()> { - let mut f = std::fs::File::create(path).map_err(|e| Error::DriverInstall(e.to_string()))?; - f.write_all(bytes) - .map_err(|e| Error::DriverInstall(e.to_string()))?; - Ok(()) } // ── Restore-mode driver watcher ────────────────────────────────────────────── @@ -574,23 +576,18 @@ impl Drop for RestoreWatcherGuard { } } -/// Spawn an elevated background watcher that force-binds our WinUSB to the Mac's +/// Spawn an elevated background watcher that binds WinUSB to the Mac's /// restore-mode interface the moment it appears. /// /// In restore mode the Mac becomes a USB composite whose data interface /// (`…&RESTORE_MODE&MI_00`) is claimed by Apple's `appleusb.inf`, whose WinUSB -/// variant libusb can't open (`winusbx_open` → ERROR_NOT_SUPPORTED). Apple's INF -/// lists that exact hardware id and is WHQL-signed, so we can't win by ranking; -/// instead we *force* our plain `winusb.sys` onto that one device instance -/// (`UpdateDriverForPlugAndPlayDevices` + `INSTALLFLAG_FORCE`), leaving -/// `appleusb.inf` in the store for iPhones. That needs admin and can only happen -/// while the device is in restore mode, so the restore relaunches this binary -/// elevated (one UAC) to run [`run_restore_mode_watch_worker`], which binds when -/// the device shows up. +/// variant libusb can't open (`winusbx_open` → ERROR_NOT_SUPPORTED). Windows +/// re-installs Apple's driver each time the Mac enters restore mode, so the +/// binding has to happen then, which needs admin: the restore relaunches this +/// binary elevated (one UAC) to run [`run_restore_mode_watch_worker`]. /// -/// Returns `None` if the watcher couldn't be launched (e.g. UAC declined) — the -/// restore still runs but will stall at "waiting for device to enter restore -/// mode". The returned guard ties the watcher's lifetime to the restore. +/// Returns `None` if the watcher couldn't be launched (e.g. UAC declined). The +/// returned guard ties the watcher's lifetime to the restore. pub fn spawn_restore_mode_watcher() -> Option { let liveness = std::env::temp_dir().join(format!( "restorekit-restore-live-{}.tmp", @@ -660,40 +657,73 @@ pub fn restore_watch_log() -> std::path::PathBuf { } /// The elevated watcher worker, invoked when this binary is rerun with -/// [`RESTORE_WATCH_ARG`]. Stages our WinUSB package (a restore can reach this -/// point without `setup-driver` ever having run: with Apple's own driver -/// installed, DFU and recovery work without it), then runs the PowerShell -/// force-bind helper as a child (inheriting this process's elevation) and -/// returns when it exits — i.e. when the restore removes the liveness file or -/// the device leaves after being bound. +/// [`RESTORE_WATCH_ARG`]. Until the restore removes the liveness file (or a +/// safety deadline passes), it binds WinUSB to: +/// +/// - the restore-mode data interface whenever it appears, and +/// - a DFU, recovery or KIS device that has had no driver for a few seconds +/// (a machine without Apple's drivers, where Windows Update hasn't run): +/// the Mac changes modes during a restore, and each mode is a new device. +/// +/// It exits early once a bound restore-mode device has left. Logs what it did +/// to [`restore_watch_log`]. pub fn run_restore_mode_watch_worker(liveness: &std::path::Path) { - use std::os::windows::process::CommandExt; - const CREATE_NO_WINDOW: u32 = 0x0800_0000; - - let log = restore_watch_log(); - let staged = match run_setup_script(true) { - Ok(()) => "staged the WinUSB package".to_string(), - Err(e) => format!("staging the WinUSB package failed: {e}"), + use std::collections::HashMap; + use std::io::Write; + use std::time::{Duration, Instant}; + + const DRIVERLESS_GRACE: Duration = Duration::from_secs(5); + let deadline = Instant::now() + Duration::from_secs(45 * 60); + let mut log = std::fs::File::create(restore_watch_log()).ok(); + let mut note = |msg: String| { + if let Some(f) = log.as_mut() { + let _ = writeln!(f, "{msg}\r"); + } }; - let _ = std::fs::write(&log, format!("{staged}\r\n")); + note("watching for restore mode".into()); - let script = std::env::temp_dir().join(format!( - "restorekit-restore-watch-{}.ps1", - std::process::id() - )); - if write_file(&script, RESTORE_WATCH_PS1.as_bytes()).is_err() { - return; + let mut driverless_since: HashMap = HashMap::new(); + let mut bound_restore = false; + while Instant::now() < deadline && liveness.exists() { + let ids = present_instance_ids().unwrap_or_default(); + let restore_present = ids + .iter() + .any(|id| id.to_ascii_uppercase().contains("&RESTORE_MODE&MI_00\\")); + if bound_restore && !restore_present { + note("restore-mode device left".into()); + break; + } + driverless_since.retain(|id, _| ids.contains(id)); + for id in &ids { + let Some(guid) = bind_guid(id) else { continue }; + if is_dongle_interface(id) || winusb::is_bound(id, guid) { + continue; + } + let restore_mode = guid == GUID_RESTORE; + if !restore_mode { + if winusb::driver_of(id).is_some() { + continue; + } + let since = *driverless_since + .entry(id.clone()) + .or_insert_with(Instant::now); + if since.elapsed() < DRIVERLESS_GRACE { + continue; + } + } + match winusb::bind(id, guid) { + Ok(()) => { + note(format!("bound WinUSB to {id}")); + bound_restore |= restore_mode; + } + Err(e) => note(format!("binding {id} failed: {e}")), + } + } + std::thread::sleep(Duration::from_millis(350)); + } + if !liveness.exists() { + note("restore ended".into()); } - let _ = Command::new("powershell") - .creation_flags(CREATE_NO_WINDOW) - .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"]) - .arg(&script) - .arg("-LivenessFile") - .arg(liveness) - .arg("-LogFile") - .arg(&log) - .status(); - let _ = std::fs::remove_file(&script); } /// Launch `exe params` elevated (UAC) with no visible window, and return without @@ -730,62 +760,6 @@ fn launch_elevated_hidden(exe: &str, params: &str) -> Result<()> { Ok(()) } -/// PowerShell watcher: find our staged INF, then poll for the restore-mode -/// device and force our WinUSB onto it (keeping `appleusb.inf` in the store). -/// Exits when the restore signals completion (liveness file gone), when the -/// device leaves after being bound, or after a safety deadline. -const RESTORE_WATCH_PS1: &str = r#"param([string]$LivenessFile, [string]$LogFile) -$ErrorActionPreference = 'SilentlyContinue' -$script:last = '' -function Log($msg) { - if ($LogFile -and $msg -ne $script:last) { Add-Content -Path $LogFile -Value ("{0:HH:mm:ss} {1}" -f (Get-Date), $msg) } - $script:last = $msg -} -Add-Type @" -using System; -using System.Runtime.InteropServices; -public static class RkNewDev { - [DllImport("newdev.dll", CharSet=CharSet.Unicode, SetLastError=true)] - public static extern bool UpdateDriverForPlugAndPlayDevices( - IntPtr hwnd, string HardwareId, string FullInfPath, uint InstallFlags, out bool bReboot); -} -"@ -# INSTALLFLAG_FORCE (0x1): install even though Apple's WHQL driver outranks ours. -# INSTALLFLAG_NONINTERACTIVE (0x4): never prompt. -$FLAGS = 0x1 -bor 0x4 -# Our newest staged WinUSB package (has the RESTORE_MODE interface entries). -$inf = (Get-ChildItem (Join-Path $env:windir 'INF\oem*.inf') -ErrorAction SilentlyContinue | Where-Object { - $c = Get-Content $_.FullName -Raw -ErrorAction SilentlyContinue - $c -match 'RestoreKit' -and $c -match 'RESTORE_MODE' -} | Sort-Object LastWriteTime -Descending | Select-Object -First 1).FullName -if (-not $inf) { Log 'no staged RestoreKit WinUSB package found'; exit 1 } -Log "using $inf" -$leaf = Split-Path $inf -Leaf -$deadline = (Get-Date).AddMinutes(45) -$bound = $false -while ((Get-Date) -lt $deadline) { - if ($LivenessFile -and -not (Test-Path $LivenessFile)) { Log 'restore ended'; break } - $dev = Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | - Where-Object { $_.InstanceId -match 'VID_05AC&PID_12[0-9A-Fa-f]{2}&RESTORE_MODE&MI_00' } | - Select-Object -First 1 - if ($dev) { - $infNow = (Get-PnpDeviceProperty -InstanceId $dev.InstanceId -KeyName DEVPKEY_Device_DriverInfPath -ErrorAction SilentlyContinue).Data - if ($infNow -ne $leaf) { - $hwid = ($dev.InstanceId -replace '\\[^\\]+$', '') - $reboot = $false - $ok = [RkNewDev]::UpdateDriverForPlugAndPlayDevices([IntPtr]::Zero, $hwid, $inf, $FLAGS, [ref]$reboot) - $code = [Runtime.InteropServices.Marshal]::GetLastWin32Error() - Log ("{0} was on {1}; bind -> ok={2} error=0x{3:X8}" -f $dev.InstanceId, $infNow, $ok, $code) - } - $bound = $true - } elseif ($bound) { - Log 'restore-mode device left' - break - } - Start-Sleep -Milliseconds 350 -} -"#; - #[cfg(test)] mod tests { use super::*; @@ -807,18 +781,43 @@ mod tests { } #[test] - fn inf_supports_both_windows_architectures_and_apple_modes() { - let inf = winusb_inf(DRIVER_PIDS); - assert!(inf.contains("Standard,NTamd64,NTarm64")); - assert!(inf.contains("[Standard.NTarm64]")); - assert!(inf.contains("USB\\VID_05AC&PID_1227")); - assert!(inf.contains("USB\\VID_05AC&PID_12AC&RESTORE_MODE&MI_00")); - assert!(inf.contains("{B8085869-FEB9-404B-8CB1-1E5C14FA8C54}")); - assert!(inf.contains("{ED82A167-D61A-4AF6-9AB6-11E52236C576}")); - assert!(inf.contains("{AF633FF1-1170-4CA6-AE9E-08D001421EAA}")); - assert!(inf.contains("{B36F4137-F4EF-4BFC-A25A-C2410768EE37}")); - assert!(inf.contains("USB\\VID_16D0&PID_14F0&MI_04\n")); - assert!(inf.contains(proto::WINUSB_INTERFACE_GUID)); + fn binds_each_mode_with_its_interface_guid() { + assert_eq!( + bind_guid("USB\\VID_05AC&PID_1227\\000445E11462001E"), + Some(GUID_DFU) + ); + assert_eq!( + bind_guid("USB\\VID_05AC&PID_1281\\SDOM:01_CPID:8132"), + Some(GUID_IBOOT) + ); + assert_eq!( + bind_guid("USB\\VID_05AC&PID_F014\\1234"), + Some(GUID_PORTDFU) + ); + assert_eq!( + bind_guid("USB\\VID_05AC&PID_1881\\5&111DD99C&0&23"), + Some(GUID_KIS) + ); + assert_eq!( + bind_guid("USB\\VID_05AC&PID_12AC&RESTORE_MODE&MI_00\\6&FC6EB5B&0&0000"), + Some(GUID_RESTORE) + ); + assert_eq!( + bind_guid("USB\\VID_16D0&PID_14F0&MI_04\\6&2E2718E1&0&0004"), + Some(proto::WINUSB_INTERFACE_GUID) + ); + // Interfaces of a recovery composite, the restore-mode NCM interface, + // and a normal-mode iPhone are never touched. + assert_eq!( + bind_guid("USB\\VID_05AC&PID_1281&MI_00\\6&109E202&0&0000"), + None + ); + assert_eq!( + bind_guid("USB\\VID_05AC&PID_12AC&RESTORE_MODE&MI_01\\6&FC6EB5B&0&0001"), + None + ); + assert_eq!(bind_guid("USB\\VID_05AC&PID_12A8\\00008101"), None); + assert_eq!(bind_guid("USB\\VID_1234&PID_1227\\OTHER"), None); } #[test] @@ -831,13 +830,4 @@ mod tests { )); assert!(!is_dongle_interface("USB\\VID_16D0&PID_14F0\\DL-6BAF14C4")); } - - #[test] - fn bind_regex_is_a_powershell_regex_over_instance_ids() { - assert_eq!( - bind_regex(), - "^USB\\\\VID_05AC&PID_(1222|1227|1280|1281|1282|1283|F014|1881)\\\\\ - |^USB\\\\VID_16D0&PID_14F0&MI_04\\\\" - ); - } } diff --git a/crates/restorekit/src/restore.rs b/crates/restorekit/src/restore.rs index 7f9270c..f3cd043 100644 --- a/crates/restorekit/src/restore.rs +++ b/crates/restorekit/src/restore.rs @@ -249,11 +249,6 @@ pub fn windows_mux_check() -> Result { otherwise close it and retry", name.unwrap_or_else(|| format!("pid {pid}")) ))), - MuxPort::Free - if crate::driver::native_arm64() && !crate::driver::winusb_package_staged() => - { - Err(Error::DriverInstall(crate::driver::ARM64_HINT.into())) - } MuxPort::Free => Ok(false), } } diff --git a/docs/windows-restore.md b/docs/windows-restore.md index a53efca..a196cd3 100644 --- a/docs/windows-restore.md +++ b/docs/windows-restore.md @@ -44,9 +44,9 @@ BaseSystem → recovered. The restore-mode phase needed three pieces: `appleusb.inf`, whose WinUSB variant libusb **can't open** (`winusbx_open` → `[50] ERROR_NOT_SUPPORTED`). Apple's INF lists that exact hardware id and is WHQL-signed, so we can't win by ranking. The fix that keeps `appleusb.inf` in - the store (iPhones unaffected): **force** our plain `winusb.sys` onto that one - device instance with `UpdateDriverForPlugAndPlayDevices(..., INSTALLFLAG_FORCE)` - — verified live, after which libusb opens it and the restore proceeds. + the store (iPhones unaffected): install Windows' own `winusb.inf` "WinUsb + Device" onto that one device instance (see "No driver package" below), + after which libusb opens it and the restore proceeds. ### Done since @@ -54,14 +54,34 @@ BaseSystem → recovered. The restore-mode phase needed three pieces: elevated watcher (one UAC, branded restorekit, skipped when already admin) that force-binds our WinUSB to the restore-mode device when it appears — per-restore, since Apple's driver reclaims it each time. `appleusb.inf` stays in the store. -- **The watcher stages the driver package itself.** With Apple's own driver - installed (iTunes, Apple Devices, or Windows Update), DFU and recovery work - without `setup-driver`, so a restore could reach restore mode with no - RestoreKit package in the store; the watcher then had nothing to bind and the - restore stalled at "waiting for device to enter restore mode" (#56). The - elevated watcher now stages the package before it starts watching, logs what - it did to `%TEMP%\restorekit-restore-watch.log`, and the restore stops up - front if the watcher can't start (UAC declined) instead of stalling later. +- **No driver package, so nothing to sign.** restorekit used to generate a + WinUSB INF, sign its catalog with a self-signed certificate it added to the + machine's trusted roots, and stage it with `pnputil`. Windows on ARM refuses + such packages outright (Code Integrity only loads Microsoft-signed ones), and + a restore could reach restore mode with no package staged (#56). Now it binds + Windows' own Microsoft-signed `winusb.inf` instead: `SetupDiBuildDriverInfoList` + over just that INF with `DI_FLAGSEX_ALLOWEXCLUDEDDRVS` (its "WinUsb Device" + entry matches `USB\MS_COMP_WINUSB`, not the Mac, which is what Device + Manager's "Have Disk" route allows too), then `DiInstallDevice` on the one + device instance, after writing the mode's interface GUID to the device's + `DeviceInterfaceGUIDs` the way an INF's `AddReg` would. A device already on + WinUSB without a GUID (a dongle on firmware 0.1.2 or older) just gets the + GUID and a restart. No certificate, no catalog, no `pnputil`, and it works + the same on x64 and ARM64. Hardware-tested on Windows 11 ARM64 with test + signing off, no Apple Mobile Device Service and no RestoreKit package or + certificate: a full revive of the M4 mini (KIS DFU via the dongle, the + watcher binding the restore-mode interface) ran to Restore Finished. +- **Device waits on Windows.** libimobiledevice-glue's Windows `cond_t` was a + semaphore, so a device event nobody was waiting for made the next wait + return at once, and idevicerestore gave up on the device; it's a real + condition variable now. `dfu_enter_recovery` also gives iBEC 60 seconds to + boot instead of 10 (see `crates/restorekit-sys/patches/README.md`). +- **The watcher binds whatever the restore needs.** The elevated watcher (log: + `%TEMP%\restorekit-restore-watch.log`) binds the restore-mode interface when + it appears, and any DFU, recovery or KIS device that has had no driver for a + few seconds (a machine without Apple's drivers), since each mode the Mac + passes through is a new device. The restore stops up front if the watcher + can't start (UAC declined) instead of stalling later. - **`setup-driver` leaves Apple's drivers alone.** Windows Update installs Apple's WHQL-signed drivers (`appleusb.inf`, `applekis.inf`) on first plug-in, and they work with restorekit (see "Driverless" below). Moving a KIS @@ -73,9 +93,6 @@ BaseSystem → recovered. The restore-mode phase needed three pieces: nusb ("Could not find DeviceInterfaceGUIDs in registry"). The next firmware adds it; `setup-driver` binds the interface with the GUID for older firmware, and runs with only a dongle connected. -- **Certificate trust.** `Import-Certificate` into - `LocalMachine\TrustedPublisher` is refused on current Windows 11 even when - elevated; the setup script uses `X509Store` instead. - **Throughput confirmed.** With the 0ms-while-connected event loop, the CLI streams `Cryptex1,systemOS` at ~35 MB/s (near USB-2.0 line rate) — the embedded usbmuxd + WinUSB bulk path is not a bottleneck. @@ -93,28 +110,17 @@ BaseSystem → recovered. The restore-mode phase needed three pieces: Hardware-tested: a full revive of an M4 mac mini (KIS DFU via a dongle) on Windows 11 ARM64 with no RestoreKit driver package, no UAC prompt and no test signing. -- **AppleKIS sometimes misses the Mac.** Entering KIS DFU from a fully booted - Mac, AppleKIS leaves its interface disabled about half the time (no - `KIS\VID_05AC&PID_0001` child), and the Mac stays unreadable until it +- **A KIS Mac sometimes comes up unreadable.** Entering KIS DFU from a fully + booted Mac, about half the time the Mac doesn't answer the driver's first + requests: AppleKIS leaves its interface disabled (no `KIS\VID_05AC&PID_0001` + child), and over WinUSB the config write fails. It stays that way until it re-enters DFU; restarting the device doesn't help. With a dongle, restorekit - now reboots the Mac out of DFU and triggers again (up to twice) when it lands - unreadable. Measured on the M4 mini: every unreadable entry read fine after - one re-entry. -- **Windows on ARM without Apple's service fails up front.** Our self-signed - package can't be staged there (see Known issues), so a restore with no Apple - Mobile Device Service and no staged package stops before uploading anything - and says to install Apple Devices or iTunes; `setup-driver` failures on ARM - say the same. + reboots the Mac out of DFU and triggers again (up to twice) when it lands + unreadable. Measured on the M4 mini over AppleKIS and WinUSB: every + unreadable entry read fine after one or two re-entries. ### Known issues -- **Windows on ARM.** Code Integrity rejects our self-signed catalog there - ("Driver package signer is not trusted by system, and Code Integrity is - enforced"), so `setup-driver` can't stage the package unless test signing is - on (`bcdedit /set testsigning on`). With Apple Mobile Device Service installed - no package is needed (see above), but a dongle on firmware 0.1.2 or older - still needs `setup-driver` for its interface GUID; update it from macOS or - Linux. - **Classic DFU (`05ac:1227`) through Apple's driver is untested here.** The rig's M4 only enters KIS DFU over the dongle. #56's log shows Port DFU, DFU and recovery going through libirecovery on Windows, but not which driver was