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/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-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 9031a5d..ae53d18 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 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.", + ); + } // 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-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-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; diff --git a/crates/restorekit-sys/build.rs b/crates/restorekit-sys/build.rs index 51c5b3c..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) }; @@ -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); } @@ -426,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() @@ -455,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; } @@ -478,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 } @@ -661,8 +669,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 +736,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 +751,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/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; 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/crates/restorekit/Cargo.toml b/crates/restorekit/Cargo.toml index d0a2f09..f998367 100644 --- a/crates/restorekit/Cargo.toml +++ b/crates/restorekit/Cargo.toml @@ -40,8 +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 c88d0cc..e3324f0 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"))] @@ -1021,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/dongle.rs b/crates/restorekit/src/dongle.rs index 44f990c..fbd22f8 100644 --- a/crates/restorekit/src/dongle.rs +++ b/crates/restorekit/src/dongle.rs @@ -505,10 +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(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) + } + })?; Ok(DongleHandle { iface, iface_num: self.vendor_iface, diff --git a/crates/restorekit/src/driver.rs b/crates/restorekit/src/driver.rs index f7835ff..2ad8123 100644 --- a/crates/restorekit/src/driver.rs +++ b/crates/restorekit/src/driver.rs @@ -1,22 +1,21 @@ -//! 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. +//! 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 std::io::Write; -use std::process::Command; +use restorekit_dongle_proto as proto; use crate::error::{Error, Result}; use crate::progress::{Event, ProgressFn}; @@ -30,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 @@ -42,10 +40,19 @@ 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) @@ -61,6 +68,34 @@ 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()) +} + +/// 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 +115,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 +143,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,236 +158,401 @@ 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. +/// 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()?; - if targets.is_empty() { + 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 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); - - // 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 output = Command::new("powershell") - .creation_flags(CREATE_NO_WINDOW) - .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"]) - .arg(&script) - .arg("-WorkDir") - .arg(&work) - .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() { - 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(); + 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}")), } + } + if !failures.is_empty() { return Err(Error::DriverInstall(format!( - "WinUSB setup did not complete: {detail}" + "WinUSB setup did not complete: {}", + failures.join("; ") ))); } - - for t in &targets { - progress(Event::DriverBound { - name: t.name.clone(), - }); - } - Ok(targets.len()) + Ok(devices.len()) } -/// 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" - )); - } - 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.1 - -[Manufacturer] -%ProviderName% = Standard,NTamd64,NTarm64 - -[Standard.NTamd64] -{models} -[Standard.NTarm64] -{models} -[WINUSB_DFU_Install.NT] -Include = winusb.inf -Needs = WINUSB.NT +/// Binding Windows' own WinUSB to one device instance. +mod winusb { + use std::os::windows::ffi::OsStrExt; + use std::ptr::{null, null_mut}; -[WINUSB_DFU_Install.NT.Services] -Include = winusb.inf -Needs = WINUSB.NT.Services + 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_DFU_Install.NT.HW] -AddReg = WINUSB_DFU_AddReg + use crate::error::{Error, Result}; -[WINUSB_DFU_AddReg] -HKR,,DeviceInterfaceGUIDs,0x10000,"{{B8085869-FEB9-404B-8CB1-1E5C14FA8C54}}" + /// `{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_IBOOT_Install.NT] -Include = winusb.inf -Needs = WINUSB.NT + fn wide(s: &str) -> Vec { + std::ffi::OsStr::new(s).encode_wide().chain([0]).collect() + } -[WINUSB_IBOOT_Install.NT.Services] -Include = winusb.inf -Needs = WINUSB.NT.Services + fn err(what: &str) -> Error { + Error::DriverInstall(format!("{what} failed: {:#x}", unsafe { GetLastError() })) + } -[WINUSB_IBOOT_Install.NT.HW] -AddReg = WINUSB_IBOOT_AddReg + /// The driver currently installed on a device. + pub(super) struct Driver { + inf: String, + provider: String, + } -[WINUSB_IBOOT_AddReg] -HKR,,DeviceInterfaceGUIDs,0x10000,"{{ED82A167-D61A-4AF6-9AB6-11E52236C576}}" + impl Driver { + pub(super) fn is_apple(&self) -> bool { + self.provider.starts_with("Apple") + } -[WINUSB_PORTDFU_Install.NT] -Include = winusb.inf -Needs = WINUSB.NT + /// 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_PORTDFU_Install.NT.Services] -Include = winusb.inf -Needs = WINUSB.NT.Services + /// An open device-info set holding one device. + struct Device { + set: HDEVINFO, + data: SP_DEVINFO_DATA, + } -[WINUSB_PORTDFU_Install.NT.HW] -AddReg = WINUSB_PORTDFU_AddReg + impl Drop for Device { + fn drop(&mut self) { + unsafe { SetupDiDestroyDeviceInfoList(self.set) }; + } + } -[WINUSB_PORTDFU_AddReg] -HKR,,DeviceInterfaceGUIDs,0x10000,"{{AF633FF1-1170-4CA6-AE9E-08D001421EAA}}" + 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_KIS_Install.NT] -Include = winusb.inf -Needs = WINUSB.NT + 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_KIS_Install.NT.Services] -Include = winusb.inf -Needs = WINUSB.NT.Services + 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_KIS_Install.NT.HW] -AddReg = WINUSB_KIS_AddReg + fn interface_guids(&self) -> Option { + let key = self.reg_key(DIREG_DEV)?; + let guids = read_string(key, "DeviceInterfaceGUIDs"); + unsafe { RegCloseKey(key) }; + guids + } -[WINUSB_KIS_AddReg] -HKR,,DeviceInterfaceGUIDs,0x10000,"{{B36F4137-F4EF-4BFC-A25A-C2410768EE37}}" + 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_RESTORE_Install.NT] -Include = winusb.inf -Needs = WINUSB.NT + /// 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_RESTORE_Install.NT.Services] -Include = winusb.inf -Needs = WINUSB.NT.Services + /// 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_RESTORE_Install.NT.HW] -AddReg = WINUSB_RESTORE_AddReg + 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])) + } -[WINUSB_RESTORE_AddReg] -HKR,,DeviceInterfaceGUIDs,0x10000,"{{3F966BD9-FA04-4EC5-991C-D326973B5128}}" + /// The driver installed on `instance_id`, if any. + pub(super) fn driver_of(instance_id: &str) -> Option { + Device::open(instance_id).ok()?.driver() + } -[Strings] -ProviderName = "RestoreKit" -DeviceName = "Apple Mobile Device (RestoreKit WinUSB)" -"# - ) -} + /// 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)) + }) + } -/// 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) -$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 -$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 -} -$svcs = Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | - Where-Object { $_.InstanceId -match 'VID_05AC' } | - 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' -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(()) + /// 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() + } + } } // ── Restore-mode driver watcher ────────────────────────────────────────────── @@ -382,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", @@ -461,29 +650,80 @@ 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`]. 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 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; + 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"); + } + }; + note("watching for restore mode".into()); + + 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) - .status(); - let _ = std::fs::remove_file(&script); } /// Launch `exe params` elevated (UAC) with no visible window, and return without @@ -520,53 +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) -$ErrorActionPreference = 'SilentlyContinue' -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 staged WinUSB package (has the RESTORE_MODE interface entries). -$inf = (Get-ChildItem C:\Windows\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 } -$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 } - $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 - [RkNewDev]::UpdateDriverForPlugAndPlayDevices([IntPtr]::Zero, $hwid, $inf, $FLAGS, [ref]$reboot) | Out-Null - } - $bound = $true - } elseif ($bound) { - break - } - Start-Sleep -Milliseconds 350 -} -"#; - #[cfg(test)] mod tests { use super::*; @@ -588,15 +781,53 @@ 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}")); + 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] + 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")); } } diff --git a/crates/restorekit/src/error.rs b/crates/restorekit/src/error.rs index 6615dd4..a1c7e0a 100644 --- a/crates/restorekit/src/error.rs +++ b/crates/restorekit/src/error.rs @@ -125,7 +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 retry" + 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" @@ -159,7 +163,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} ...") } diff --git a/crates/restorekit/src/kis.rs b/crates/restorekit/src/kis.rs index 42d28a0..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)); @@ -100,6 +113,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 +229,168 @@ 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 +/// 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; + + 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; + + pub(super) fn read(info: &nusb::DeviceInfo) -> Read { + match get_info(info) { + Some(reply) => classify_apple_kis(&reply), + None => Read::Failed, + } + } + + /// 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 >= APPLE_KIS_SERIAL_END).then_some(reply) + } + } +} + /// A KIS portal: a bulk OUT/IN endpoint pair. #[cfg(not(target_os = "macos"))] struct Portal { @@ -543,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 b7ff7d7..f3cd043 100644 --- a/crates/restorekit/src/restore.rs +++ b/crates/restorekit/src/restore.rs @@ -235,6 +235,24 @@ 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 => Ok(false), + } +} + /// Run a restore against the DFU device with the given ECID, streaming progress. /// /// This links libidevicerestore statically; there is no external binary. @@ -254,8 +272,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() && windows_mux_check()?; + #[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)?) @@ -264,8 +292,21 @@ 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 = 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..4abb9af 100644 --- a/crates/restorekit/src/usbmuxd.rs +++ b/crates/restorekit/src/usbmuxd.rs @@ -12,6 +12,153 @@ use std::thread::{self, JoinHandle}; use crate::error::{Error, Result}; use crate::progress::{Event, ProgressFn}; +/// 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.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]]); + (row_port == port && (addr == [127, 0, 0, 1] || addr == [0, 0, 0, 0])).then_some(pid) + }) +} + +#[cfg(target_os = "windows")] +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. pub struct UsbmuxdGuard { /// The Unix socket file to clean up (Linux only). @@ -101,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/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 diff --git a/docs/windows-restore.md b/docs/windows-restore.md index 01822d3..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,12 +54,78 @@ 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. +- **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 + 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 + it; `setup-driver` binds the interface with the GUID for older firmware, and + runs with only a dongle connected. - **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. +- **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 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. 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. +- **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 + 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 +- **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 packets/sec). The C/USB stack is identical, so the throttle is somewhere in the