diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1cf4931..5527048 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -114,9 +114,9 @@ jobs: ~/.cargo/registry/cache ~/.cargo/git/db target - key: rust-ci-${{ matrix.os }}-${{ steps.toolchain.outputs.version }}-${{ steps.pins.outputs.hash }}-${{ hashFiles('crates/restorekit-sys/build.rs') }}-${{ hashFiles('Cargo.lock') }} + key: rust-ci-${{ matrix.os }}-${{ steps.toolchain.outputs.version }}-${{ steps.pins.outputs.hash }}-${{ hashFiles('crates/restorekit-sys/build.rs', 'crates/restorekit-sys/patches/**') }}-${{ hashFiles('Cargo.lock') }} restore-keys: | - rust-ci-${{ matrix.os }}-${{ steps.toolchain.outputs.version }}-${{ steps.pins.outputs.hash }}-${{ hashFiles('crates/restorekit-sys/build.rs') }}- + rust-ci-${{ matrix.os }}-${{ steps.toolchain.outputs.version }}-${{ steps.pins.outputs.hash }}-${{ hashFiles('crates/restorekit-sys/build.rs', 'crates/restorekit-sys/patches/**') }}- - name: Format run: cargo fmt --all --check @@ -218,9 +218,9 @@ jobs: ~/.cargo/registry/cache ~/.cargo/git/db target - key: rust-ci-windows-gnu-${{ steps.toolchain.outputs.version }}-${{ steps.pins.outputs.hash }}-${{ hashFiles('crates/restorekit-sys/build.rs') }}-${{ hashFiles('Cargo.lock') }} + key: rust-ci-windows-gnu-${{ steps.toolchain.outputs.version }}-${{ steps.pins.outputs.hash }}-${{ hashFiles('crates/restorekit-sys/build.rs', 'crates/restorekit-sys/patches/**') }}-${{ hashFiles('Cargo.lock') }} restore-keys: | - rust-ci-windows-gnu-${{ steps.toolchain.outputs.version }}-${{ steps.pins.outputs.hash }}-${{ hashFiles('crates/restorekit-sys/build.rs') }}- + rust-ci-windows-gnu-${{ steps.toolchain.outputs.version }}-${{ steps.pins.outputs.hash }}-${{ hashFiles('crates/restorekit-sys/build.rs', 'crates/restorekit-sys/patches/**') }}- # The target cache above carries the staging prefix too, but it's # multi-GB and first in line for LRU eviction under the repo's 10 GB @@ -235,7 +235,7 @@ jobs: uses: actions/cache@v4 with: path: target/x86_64-pc-windows-gnu/debug/build/restorekit-sys-*/out/staging - key: windows-c-stack-${{ steps.pins.outputs.hash }}-${{ steps.toolchain.outputs.version }}-${{ hashFiles('crates/restorekit-sys/build.rs', 'Cargo.lock') }} + key: windows-c-stack-${{ steps.pins.outputs.hash }}-${{ steps.toolchain.outputs.version }}-${{ hashFiles('crates/restorekit-sys/build.rs', 'crates/restorekit-sys/patches/**', 'Cargo.lock') }} # With both caches hot, nothing runs autotools (staging markers skip the # C stack) or rebuilds openssl-src (the target cache has it), so the full diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index 046c65c..9a39d21 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -14,7 +14,7 @@ const DONGLE_DFU_TIMEOUT: Duration = Duration::from_secs(60); /// string so the backend can re-derive the exact ECID without a float round-trip. #[derive(Serialize)] pub struct DeviceView { - /// "dfu" | "port-dfu" | "recovery" | "wtf" | "restore" | "booted" | + /// "dfu" | "port-dfu" | "kis" | "recovery" | "wtf" | "restore" | "booted" | /// "billboard" | "other" pub mode: String, pub name: String, diff --git a/apps/desktop/src/App.svelte b/apps/desktop/src/App.svelte index 681f455..373e4d4 100644 --- a/apps/desktop/src/App.svelte +++ b/apps/desktop/src/App.svelte @@ -201,6 +201,9 @@ // or manual instructions. function deviceMode(d: Device): "restore" | "usb" | "dfu" | "manual" { if (d.restorable) return d.driver_ready ? "restore" : "usb"; + // Already in DFU over Debug USB, just unreadable here: + // re-triggering can't help. + if (d.mode === "kis") return d.driver_ready ? "manual" : "usb"; // A Mac behind a dongle can be put into DFU over the dongle from any host, // even when this host can't trigger electronically. return canTrigger || d.via_dongle ? "dfu" : "manual"; @@ -233,6 +236,7 @@ const MODE_TAG: Record = { dfu: "DFU", "port-dfu": "Port DFU", + kis: "Debug USB DFU", recovery: "Recovery", restore: "Restore", wtf: "WTF", @@ -243,6 +247,7 @@ const MODE_COLOR: Record = { dfu: "var(--acc)", "port-dfu": "var(--acc)", + kis: "var(--acc)", recovery: "var(--alt)", restore: "var(--ok)", wtf: "var(--danger)", @@ -1287,6 +1292,17 @@ + {:else if selected.mode === "kis"} +
+ {#if isMac} +

This Mac is in DFU over Debug USB, but restorekit couldn't read its identity. Usually another app has the device open (Chrome, Apple Configurator). Quit it, then reboot the Mac and put it back into DFU.

+ {:else} +

This Mac is in DFU over Debug USB, but restorekit couldn't read its identity. Check USB access, then reboot the Mac and put it back into DFU.

+ {/if} +
+ +
+
{:else}

This host can't trigger DFU. Put the target into DFU by hand:

diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts index 0c78302..0f76ce8 100644 --- a/apps/desktop/src/lib/api.ts +++ b/apps/desktop/src/lib/api.ts @@ -3,7 +3,7 @@ import { listen, type UnlistenFn } from "@tauri-apps/api/event"; import { downloadDir, join } from "@tauri-apps/api/path"; import { open, save } from "@tauri-apps/plugin-dialog"; -export type Mode = "dfu" | "port-dfu" | "recovery" | "wtf" | "restore" | "booted" | "billboard" | "other"; +export type Mode = "dfu" | "port-dfu" | "kis" | "recovery" | "wtf" | "restore" | "booted" | "billboard" | "other"; /** The host USB-C port a device is cabled to (macOS only). */ export interface Port { @@ -339,6 +339,7 @@ export function gib(bytes: number): string { export const MODES: Record = { dfu: { label: "DFU", hint: "ready to restore" }, "port-dfu": { label: "Port DFU", hint: "ready to update the port and restore" }, + kis: { label: "Debug USB DFU", hint: "DFU over Apple's Debug USB interface" }, recovery: { label: "Recovery", hint: "put in DFU to restore" }, restore: { label: "Restore", hint: "restore in progress" }, wtf: { label: "WTF", hint: "low-level mode" }, diff --git a/crates/restorekit-cli/src/commands/dfu.rs b/crates/restorekit-cli/src/commands/dfu.rs index a42d430..aeff84b 100644 --- a/crates/restorekit-cli/src/commands/dfu.rs +++ b/crates/restorekit-cli/src/commands/dfu.rs @@ -93,6 +93,9 @@ pub fn enter( Ok(DfuOutcome::Entered(device)) => { if json { emit_stage(true, Event::DeviceDetected { device }); + } else if device.kis_unreadable() { + println!("\nTarget is now in DFU mode over Debug USB (05ac:1881)."); + println!(" Note: {}", Error::KisUnreadable); } else { println!("\nTarget is now in DFU mode: {}", device.display_name()); println!(" ECID: {}", device.ecid_hex().unwrap_or_default()); @@ -305,6 +308,43 @@ pub fn probe_ports(json: bool) -> Result<()> { Ok(()) } +/// `restorekit vdm` — send one raw VDM and dump the reply register. +pub fn raw_vdm(json: bool, words: &[u32], port: Option) -> Result<()> { + let target = port + .map(restorekit::dfu::DfuTarget::Port) + .unwrap_or_default(); + let reply = restorekit::dfu::raw_vdm(&target, words, &mut |e| emit_stage(json, e))?; + let status = reply[0]; + let count = (status & 0x07) as usize; + let all: Vec = reply[1..61] + .as_chunks::<4>() + .0 + .iter() + .map(|c| u32::from_le_bytes(*c)) + .collect(); + if json { + println!( + "{}", + serde_json::json!({ "event": "vdm_reply", "status": status, "words": all }) + ); + return Ok(()); + } + let kind = match all[0] & 0xc0 { + 0x40 => "ACK", + 0x80 => "NAK", + 0xc0 => "BUSY", + _ => "REQ", + }; + println!("status 0x{status:02x}, header 0x{:08x} ({kind})", all[0]); + for (i, w) in all.iter().enumerate().skip(1) { + let mark = if i < count { "" } else { " (past count)" }; + if i < count || *w != 0 { + println!(" [{i}] 0x{w:08x}{mark}"); + } + } + Ok(()) +} + /// Ensure a Mac is in DFU mode: return it if already there (with the interactive /// picker when several are present and no ECID pins one), otherwise trigger /// entry via a dongle or the host and wait. Shared by `restore`. @@ -338,6 +378,11 @@ pub(crate) fn ensure_present( if !present.is_empty() { 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) { + return Err(Error::KisUnreadable); + } // Name a target visible in another mode so the user knows the trigger // has something to act on. if !json { @@ -361,6 +406,7 @@ pub(crate) fn ensure_present( /// cabled here, or a wait for a manual DFU entry when nothing can trigger. fn finish_trigger(json: bool, via: DfuVia, timeout: Duration, ecid: Option) -> Result { match restorekit::trigger_dfu(via, timeout, &mut |e| emit_stage(json, e)) { + Ok(DfuOutcome::Entered(dev)) if dev.kis_unreadable() => Err(Error::KisUnreadable), Ok(DfuOutcome::Entered(dev)) => Ok(dev), Ok(DfuOutcome::Sent) => Err(Error::Dongle( "triggered via dongle, but the target's USB data isn't cabled to this host; \ diff --git a/crates/restorekit-cli/src/commands/list.rs b/crates/restorekit-cli/src/commands/list.rs index 05d5ae1..88af835 100644 --- a/crates/restorekit-cli/src/commands/list.rs +++ b/crates/restorekit-cli/src/commands/list.rs @@ -198,7 +198,18 @@ fn run_once(json: bool) -> Result<()> { print_ports(); print_dongles(); - if !devices.iter().any(|d| d.restorable()) { + if devices.iter().any(|d| d.kis_unreadable()) { + println!( + "Can't restore the Mac in DFU over Debug USB: {}", + restorekit::Error::KisUnreadable + ); + } else if !devices.iter().any(|d| d.restorable()) { + if devices.iter().any(|d| d.debug_usb_not_in_dfu()) { + println!( + "Debug USB is on, but the device behind it isn't in DFU, so there's no identity \ + to read." + ); + } println!("None are in DFU mode; only a Mac in DFU mode can be restored."); if restorekit::host_can_trigger_dfu() { println!("Run `restorekit dfu` to put the cabled target into DFU mode."); diff --git a/crates/restorekit-cli/src/main.rs b/crates/restorekit-cli/src/main.rs index ac96bb9..57f7b63 100644 --- a/crates/restorekit-cli/src/main.rs +++ b/crates/restorekit-cli/src/main.rs @@ -44,6 +44,22 @@ enum Command { /// Diagnostic — sends no DFU action. Hidden. #[command(hide = true)] ProbePorts, + /// Dump what restorekit reads from Debug USB (KIS, 05ac:1881) devices: the + /// raw GET_INFO reply and, on macOS, what deviceinterfaced reports. + /// Diagnostic. Hidden. + #[command(hide = true)] + KisProbe, + /// Send one raw USB-PD VDM to the partner on a host DFU port and print the + /// reply (Apple Silicon macOS, root). Diagnostic. Hidden. + #[command(hide = true)] + Vdm { + /// VDM words in hex, header first (e.g. 0x05ac8010). + #[arg(required = true, value_parser = parse_hex_u32)] + words: Vec, + /// Host DFU-capable port RID (defaults to the DFU port). + #[arg(long)] + port: Option, + }, /// Resolve and download firmware for the detected (or specified) Mac. Download { /// Model identifier (e.g. MacBookPro17,1). Defaults to the DFU device. @@ -240,6 +256,11 @@ struct ReviveArgs { } /// Parse an ECID: `0x`-prefixed or bare hex, or decimal. +fn parse_hex_u32(s: &str) -> Result { + let hex = s.trim().trim_start_matches("0x").trim_start_matches("0X"); + u32::from_str_radix(hex, 16).map_err(|e| format!("invalid hex word {s:?}: {e}")) +} + fn parse_ecid(s: &str) -> Result { let s = s.trim(); let parsed = if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) { @@ -307,6 +328,11 @@ fn main() { Command::Reboot(t) => commands::dfu::reboot(cli.json, t.dongle, t.ecid, t.port), Command::Serial(t) => commands::dfu::serial(cli.json, t.dongle, t.ecid, t.port), Command::ProbePorts => commands::dfu::probe_ports(cli.json), + Command::KisProbe => { + print!("{}", restorekit::kis::probe()); + Ok(()) + } + Command::Vdm { words, port } => commands::dfu::raw_vdm(cli.json, &words, port), Command::Download { identifier, os_version, diff --git a/crates/restorekit-sys/build.rs b/crates/restorekit-sys/build.rs index 4adc0ea..51c5b3c 100644 --- a/crates/restorekit-sys/build.rs +++ b/crates/restorekit-sys/build.rs @@ -56,7 +56,12 @@ fn main() { ("libtatsu", "1.0.5"), ("libimobiledevice", "1.4.0"), ] { - build_autotools(&vendor.join(lib), lib, version, &deps); + let src = if lib == "libirecovery" { + patch_libirecovery_sources(&manifest, &vendor.join(lib), &out, &deps) + } else { + vendor.join(lib) + }; + build_autotools(&src, lib, version, &deps); } // idevicerestore: compile its sources directly (no library upstream), @@ -276,7 +281,8 @@ fn build_autotools(src: &Path, name: &str, version: &str, deps: &Deps) { // adds -lsetupapi for host_os mingw32*, but under the MSYS2 shell the // host detects as msys, so irecovery.exe fails to link SetupDi*). The // static libraries we ultimately link are archives and unaffected. - configure.env("LIBS", "-lws2_32 -liphlpapi -lole32 -lsetupapi"); + // winusb: libirecovery's KIS-over-WinUSB patch (irecovery.exe links it). + configure.env("LIBS", "-lws2_32 -liphlpapi -lole32 -lsetupapi -lwinusb"); } run(&mut configure, &format!("{name} configure")); if deps.windows { @@ -420,6 +426,101 @@ 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. +/// 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( + manifest: &Path, + vendor_src: &Path, + out: &Path, + deps: &Deps, +) -> PathBuf { + use std::hash::{Hash, Hasher}; + + let patch_dir = manifest.join("patches/libirecovery"); + println!("cargo:rerun-if-changed={}", patch_dir.display()); + let mut patches: Vec = std::fs::read_dir(&patch_dir) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("patch")) + .collect(); + patches.sort(); + + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + for patch in &patches { + println!("cargo:rerun-if-changed={}", patch.display()); + std::fs::read(patch).unwrap().hash(&mut hasher); + } + 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"); + if marker.exists() && std::fs::read_to_string(&stamp_file).is_ok_and(|s| s == stamp) { + return root; + } + + if root.exists() { + std::fs::remove_dir_all(&root).unwrap(); + } + copy_tree(vendor_src, &root); + for patch in &patches { + // POSIX `patch`, not `git apply`; see patch_idevicerestore_sources. + run( + Command::new("patch") + .args(["-p1", "--no-backup-if-mismatch", "-i"]) + .arg(patch) + .current_dir(&root), + &format!("apply {}", patch.file_name().unwrap().to_string_lossy()), + ); + } + // 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")); + std::fs::write(&stamp_file, stamp).unwrap(); + root +} + +/// Recursively copy `src` to `dst`, skipping `.git` (a submodule's `.git` is a +/// file pointing back into the superproject, which a copy can't follow) and +/// autotools output left by an earlier in-tree autogen. A copy gets fresh +/// mtimes, so stale generated files could look out of date and make `make` +/// re-run automake; leaving them out makes build_autotools regenerate them. +/// Symlinks are skipped too: the upstream trees track none, but autogen on +/// macOS links its aux files (`ltmain.sh`, `config.guess`, …) into Homebrew. +fn copy_tree(src: &Path, dst: &Path) { + std::fs::create_dir_all(dst).unwrap(); + for entry in std::fs::read_dir(src).unwrap() { + let entry = entry.unwrap(); + let name = entry.file_name(); + if matches!( + name.to_str(), + Some( + ".git" + | "autom4te.cache" + | "configure" + | "aclocal.m4" + | "Makefile.in" + | "config.h.in" + ) + ) { + continue; + } + let path = entry.path(); + let kind = entry.file_type().unwrap(); + if kind.is_symlink() { + continue; + } + if kind.is_dir() { + copy_tree(&path, &dst.join(&name)); + } else { + std::fs::copy(&path, dst.join(&name)).unwrap(); + } + } +} + /// Compile idevicerestore's own C sources into a static archive and link it. fn compile_idevicerestore(src: &Path, deps: &Deps) { let src_dir = src.join("src"); @@ -633,7 +734,7 @@ fn emit_link_directives(prefix: &Path) { println!("cargo:rustc-link-lib=static=usb-1.0"); for lib in [ "setupapi", "ole32", "ws2_32", "crypt32", "secur32", "bcrypt", "iphlpapi", "userenv", - "advapi32", + "advapi32", "winusb", ] { println!("cargo:rustc-link-lib=dylib={lib}"); } diff --git a/crates/restorekit-sys/patches/README.md b/crates/restorekit-sys/patches/README.md index 9e8b41e..2748f65 100644 --- a/crates/restorekit-sys/patches/README.md +++ b/crates/restorekit-sys/patches/README.md @@ -30,6 +30,27 @@ compiles the patched copy. "Unable to discover device mode" while the Mac was still on its way back. Loop until the mode is known or the minute is up. +## libirecovery + +- `0001-kis-via-deviceinterfaced-on-macos.patch` — macOS only lets processes + holding `com.apple.private.debug-usb.access` open a Debug USB (KIS, + `05ac:1881`) device, and only Apple's `deviceinterfaced` has it. On macOS, + open KIS devices through the daemon's private `DeviceInterfaceClient` + framework and send KIS requests with its `transfer_data`, instead of failing + to open the device (or dropping its device-add event). Loaded at runtime; + `IRECV_KIS_NO_DIC=1` forces the plain IOKit path. Unlike idevicerestore, + libirecovery is built with autotools from a patched copy of the whole tree, + rebuilt only when the patches change. +- `0002-kis-over-winusb-on-windows.patch` — libirecovery's Windows KIS code + talks to Apple's AppleKIS driver, which does the KIS framing itself behind + its own ioctls. restorekit binds plain WinUSB to `05ac:1881` instead, so a + KIS device was never found. When the KIS interface turns out to be a WinUSB + device, speak raw KIS on its bulk pipes through `WinUsb_*` (the same requests + the libusb and IOKit backends send). The SetupAPI device checks (open, add + and the hotplug poller) accept pid `1881` next to AppleKIS's pid 1, so + idevicerestore gets the device-add event it reads the mode from. The AppleKIS + path is untouched. + ## Updating a patch 1. Apply the existing patches to the submodule: diff --git a/crates/restorekit-sys/patches/libirecovery/0001-kis-via-deviceinterfaced-on-macos.patch b/crates/restorekit-sys/patches/libirecovery/0001-kis-via-deviceinterfaced-on-macos.patch new file mode 100644 index 0000000..791b358 --- /dev/null +++ b/crates/restorekit-sys/patches/libirecovery/0001-kis-via-deviceinterfaced-on-macos.patch @@ -0,0 +1,389 @@ +--- a/src/libirecovery.c ++++ b/src/libirecovery.c +@@ -46,6 +46,10 @@ + #include + #include + #include ++#include ++#include ++#include ++#include + #endif + #else + #define WIN32_LEAN_AND_MEAN +@@ -128,6 +132,8 @@ + IOUSBDeviceInterface320 **handle; + IOUSBInterfaceInterface300 **usbInterface; + CFRunLoopSourceRef async_event_source; ++ int kis_dic; ++ uint64_t kis_dic_id; + #endif + #else + HANDLE handle; +@@ -762,6 +768,10 @@ + #ifdef HAVE_IOKIT + static int iokit_get_string_descriptor_ascii(irecv_client_t client, uint8_t desc_index, unsigned char * buffer, int size) + { ++ if (client->kis_dic) { ++ /* No USB handle: deviceinterfaced owns the device. */ ++ return IRECV_E_UNSUPPORTED; ++ } + IOReturn result; + IOUSBDevRequest request; + unsigned char descriptor[256]; +@@ -1063,10 +1073,187 @@ + hdr->reqSize = (uint32_t) reqSize; + + return IRECV_E_SUCCESS; ++} ++ ++#ifdef HAVE_IOKIT ++/* ++ * macOS only lets processes holding com.apple.private.debug-usb.access open a ++ * Debug USB (KIS) device, and only Apple's deviceinterfaced has it. The daemon ++ * does expose a generic KIS transport to any client through ++ * DeviceInterfaceClient.framework, so route KIS requests through that instead ++ * of opening the device ourselves. The framework is private, so it's loaded at ++ * runtime and every failure falls back to the plain IOKit path. ++ */ ++#define DIC_FRAMEWORK "/Library/Apple/System/Library/PrivateFrameworks/DeviceInterfaceClient.framework/DeviceInterfaceClient" ++#define DIC_MAX_SCALARS 16 ++ ++static struct { ++ void *client; ++ bool (*list_devices)(void *client, uint64_t *ids, size_t *count); ++ bool (*transfer_data)(void *client, uint64_t id, const uint64_t *scalars, uint32_t scalar_count, const void *in, size_t in_size, void *out, size_t *out_size); ++} dic; ++static pthread_once_t dic_once = PTHREAD_ONCE_INIT; ++static uint32_t dic_sequence; ++ ++static void dic_load_once(void) ++{ ++ if (getenv("IRECV_KIS_NO_DIC")) { ++ return; ++ } ++ void *h = dlopen(DIC_FRAMEWORK, RTLD_NOW | RTLD_LOCAL); ++ if (!h) { ++ debug("%s: DeviceInterfaceClient unavailable: %s\n", __func__, dlerror()); ++ return; ++ } ++ void *(*create)(dispatch_queue_t) = dlsym(h, "device_interface_client_server_xpc_client_create"); ++ dic.list_devices = dlsym(h, "device_interface_client_server_xpc_client_list_devices"); ++ dic.transfer_data = dlsym(h, "device_interface_client_server_xpc_client_transfer_data"); ++ if (!create || !dic.list_devices || !dic.transfer_data) { ++ debug("%s: DeviceInterfaceClient is missing expected symbols\n", __func__); ++ return; ++ } ++ dic.client = create(dispatch_queue_create("libirecovery.kis", DISPATCH_QUEUE_SERIAL)); ++ if (!dic.client) { ++ debug("%s: could not connect to deviceinterfaced\n", __func__); ++ } + } + ++static int dic_available(void) ++{ ++ pthread_once(&dic_once, dic_load_once); ++ return dic.client != NULL; ++} ++ ++static uint16_t iokit_registry_pid(io_service_t service) ++{ ++ uint16_t pid = 0; ++ CFNumberRef num = (CFNumberRef)IORegistryEntryCreateCFProperty(service, CFSTR(kUSBProductID), kCFAllocatorDefault, 0); ++ if (num) { ++ CFNumberGetValue(num, kCFNumberSInt16Type, &pid); ++ CFRelease(num); ++ } ++ return pid; ++} ++ ++/* deviceinterfaced names interfaces by an opaque 64-bit id. Match it against ++ * the registry entry ids of the device and its interfaces; failing that, a lone ++ * interface can only be this device. */ ++static uint64_t dic_find_interface(io_service_t service) ++{ ++ uint64_t ids[16]; ++ size_t count = sizeof(ids) / sizeof(ids[0]); ++ if (!dic.list_devices(dic.client, ids, &count) || count == 0) { ++ debug("%s: deviceinterfaced lists no KIS interfaces\n", __func__); ++ return 0; ++ } ++ if (count > sizeof(ids) / sizeof(ids[0])) { ++ count = sizeof(ids) / sizeof(ids[0]); ++ } ++ ++ uint64_t entry = 0; ++ if (IORegistryEntryGetRegistryEntryID(service, &entry) == KERN_SUCCESS) { ++ for (size_t i = 0; i < count; i++) { ++ if (ids[i] == entry) { ++ return ids[i]; ++ } ++ } ++ } ++ io_iterator_t children = IO_OBJECT_NULL; ++ if (IORegistryEntryGetChildIterator(service, kIOServicePlane, &children) == KERN_SUCCESS) { ++ io_registry_entry_t child; ++ uint64_t found = 0; ++ while (!found && (child = IOIteratorNext(children))) { ++ if (IORegistryEntryGetRegistryEntryID(child, &entry) == KERN_SUCCESS) { ++ for (size_t i = 0; i < count; i++) { ++ if (ids[i] == entry) { ++ found = ids[i]; ++ break; ++ } ++ } ++ } ++ IOObjectRelease(child); ++ } ++ IOObjectRelease(children); ++ if (found) { ++ return found; ++ } ++ } ++ if (count == 1) { ++ return ids[0]; ++ } ++ debug("%s: %zu KIS interfaces and none match this device\n", __func__, count); ++ return 0; ++} ++ ++/* Takes ownership of `service`, like iokit_usb_open_service. */ ++static irecv_error_t dic_open_service(irecv_client_t *pclient, io_service_t service) ++{ ++ uint64_t id = dic_find_interface(service); ++ IOObjectRelease(service); ++ if (!id) { ++ return IRECV_E_UNABLE_TO_CONNECT; ++ } ++ irecv_client_t client = (irecv_client_t)calloc(1, sizeof(struct irecv_client_private)); ++ if (!client) { ++ return IRECV_E_OUT_OF_MEMORY; ++ } ++ client->mode = KIS_PRODUCT_ID; ++ client->kis_dic = 1; ++ client->kis_dic_id = id; ++ debug("opening KIS device via deviceinterfaced (interface %#" PRIx64 ")...\n", id); ++ *pclient = client; ++ return IRECV_E_SUCCESS; ++} ++ ++static irecv_error_t dic_kis_request(irecv_client_t client, KIS_req_header *req, size_t reqSize, KIS_req_header *rpl, size_t *rplSize) ++{ ++ if (reqSize < sizeof(KIS_req_header)) { ++ return IRECV_E_INVALID_INPUT; ++ } ++ ++ /* The daemon matches replies to requests by their first header word and ++ * uses 0xFFxx sequence numbers for its own requests. Stay in 1..0x7FFF; ++ * restorekit's own identity reads use 0x8000 and up. */ ++ req->sequence = (uint16_t)(__atomic_add_fetch(&dic_sequence, 1, __ATOMIC_RELAXED) % 0x7FFF + 1); ++ ++ /* The daemon writes scalars[1..] out as little-endian 32-bit words followed ++ * by the input bytes, so the header and arguments go in as scalars and any ++ * payload as input. scalars[0] is the timeout in milliseconds. */ ++ const uint8_t *bytes = (const uint8_t *)req; ++ size_t words = 3 + req->argCount; ++ if (words > DIC_MAX_SCALARS - 1) { ++ words = DIC_MAX_SCALARS - 1; ++ } ++ if (words * 4 > reqSize) { ++ words = reqSize / 4; ++ } ++ uint64_t scalars[DIC_MAX_SCALARS]; ++ scalars[0] = USB_TIMEOUT; ++ for (size_t i = 0; i < words; i++) { ++ uint32_t w; ++ memcpy(&w, bytes + i * 4, 4); ++ scalars[1 + i] = w; ++ } ++ const void *in = (reqSize > words * 4) ? bytes + words * 4 : NULL; ++ size_t in_size = reqSize - words * 4; ++ ++ size_t out_size = *rplSize; ++ if (!dic.transfer_data(dic.client, client->kis_dic_id, scalars, (uint32_t)(1 + words), in, in_size, rpl, &out_size)) { ++ debug("%s: deviceinterfaced transfer failed (portal %#x)\n", __func__, req->portal); ++ return IRECV_E_USB_UPLOAD; ++ } ++ *rplSize = out_size; ++ return IRECV_E_SUCCESS; ++} ++#endif ++ + static irecv_error_t irecv_kis_request(irecv_client_t client, KIS_req_header *req, size_t reqSize, KIS_req_header *rpl, size_t *rplSize) + { ++#ifdef HAVE_IOKIT ++ if (client->kis_dic) { ++ return dic_kis_request(client, req, reqSize, rpl, rplSize); ++ } ++#endif + int endpoint = 0; + switch (req->portal) { + case KIS_PORTAL_CONFIG: +@@ -1203,6 +1390,13 @@ + + static irecv_error_t irecv_kis_init(irecv_client_t client) + { ++#ifdef HAVE_IOKIT ++ /* deviceinterfaced enables the device itself when it attaches. */ ++ if (client->kis_dic) { ++ client->isKIS = 1; ++ return IRECV_E_SUCCESS; ++ } ++#endif + #ifndef _WIN32 + irecv_error_t err = irecv_kis_config_write32(client, KIS_PORTAL_CONFIG, KIS_INDEX_ENABLE_A, KIS_ENABLE_A_VAL); + if (err != IRECV_E_SUCCESS) { +@@ -1479,9 +1673,17 @@ + + static int check_context(irecv_client_t client) + { +- if (client == NULL || client->handle == NULL) { ++ if (client == NULL) { + return IRECV_E_NO_DEVICE; + } ++#ifdef HAVE_IOKIT ++ if (client->kis_dic) { ++ return IRECV_E_SUCCESS; ++ } ++#endif ++ if (client->handle == NULL) { ++ return IRECV_E_NO_DEVICE; ++ } + + return IRECV_E_SUCCESS; + } +@@ -1491,6 +1693,10 @@ + #ifdef HAVE_IOKIT + static int iokit_usb_control_transfer(irecv_client_t client, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, unsigned char *data, uint16_t w_length, unsigned int timeout) + { ++ if (client->kis_dic) { ++ /* No USB handle: deviceinterfaced owns the device. */ ++ return IRECV_E_UNSUPPORTED; ++ } + IOReturn result; + IOUSBDevRequestTO req; + +@@ -1593,6 +1799,10 @@ + + static int iokit_async_usb_control_transfer(irecv_client_t client, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, unsigned char *data, uint16_t w_length, struct irecv_async_transfer* transfer) + { ++ if (client->kis_dic) { ++ /* No USB handle: deviceinterfaced owns the device. */ ++ return IRECV_E_UNSUPPORTED; ++ } + IOReturn result; + IOUSBDevRequest req; + +@@ -1740,6 +1950,10 @@ + int *transferred, + unsigned int timeout) + { ++ if (client->kis_dic) { ++ /* No USB handle: deviceinterfaced owns the device. */ ++ return IRECV_E_UNSUPPORTED; ++ } + IOReturn result; + IOUSBInterfaceInterface300 **intf = client->usbInterface; + UInt32 size = length; +@@ -1952,6 +2166,10 @@ + IOCFPlugInInterface **plug = NULL; + CFStringRef serialString; + ++ if (iokit_registry_pid(service) == KIS_PRODUCT_ID && dic_available()) { ++ return dic_open_service(pclient, service); ++ } ++ + client = (irecv_client_t) calloc( 1, sizeof(struct irecv_client_private)); + + // Create the plug-in +@@ -2245,13 +2463,15 @@ + } + + #ifdef HAVE_IOKIT +- error = (*client->handle)->CreateDeviceAsyncEventSource(client->handle, &client->async_event_source); +- if (error != IRECV_E_SUCCESS) { +- free(client); +- *pclient = NULL; +- return error; ++ if (!client->kis_dic) { ++ error = (*client->handle)->CreateDeviceAsyncEventSource(client->handle, &client->async_event_source); ++ if (error != IRECV_E_SUCCESS) { ++ free(client); ++ *pclient = NULL; ++ return error; ++ } ++ CFRunLoopAddSource(CFRunLoopGetCurrent(), client->async_event_source, kCFRunLoopDefaultMode); + } +- CFRunLoopAddSource(CFRunLoopGetCurrent(), client->async_event_source, kCFRunLoopDefaultMode); + #endif + + if (client->mode == IRECV_K_DFU_MODE || client->mode == IRECV_K_PORT_DFU_MODE || client->mode == IRECV_K_WTF_MODE || client->mode == KIS_PRODUCT_ID) { +@@ -2323,6 +2543,10 @@ + debug("Setting to configuration %d\n", configuration); + + #ifdef HAVE_IOKIT ++ if (client->kis_dic) { ++ client->usb_config = configuration; ++ return IRECV_E_SUCCESS; ++ } + IOReturn result; + + result = (*client->handle)->SetConfiguration(client->handle, configuration); +@@ -2440,6 +2664,11 @@ + debug("Setting to interface %d:%d\n", usb_interface, usb_alt_interface); + #ifndef _WIN32 + #ifdef HAVE_IOKIT ++ if (client->kis_dic) { ++ client->usb_interface = usb_interface; ++ client->usb_alt_interface = usb_alt_interface; ++ return IRECV_E_SUCCESS; ++ } + if (iokit_usb_set_interface(client, usb_interface, usb_alt_interface) < 0) { + return IRECV_E_USB_INTERFACE; + } +@@ -2478,6 +2707,9 @@ + + #ifndef _WIN32 + #ifdef HAVE_IOKIT ++ if (client->kis_dic) { ++ return IRECV_E_SUCCESS; ++ } + IOReturn result; + + result = (*client->handle)->ResetDevice(client->handle); +@@ -2770,12 +3002,12 @@ + debug("%s: ERROR: no device?!\n", __func__); + return NULL; + } +- if (!dev) { +- debug("%s: ERROR: no device interface?!\n", __func__); +- return NULL; ++ if (dev) { ++ (*dev)->GetDeviceProduct(dev, &product_id); ++ } else { ++ /* KIS devices reach here without one; see iokit_device_added. */ ++ product_id = iokit_registry_pid(device); + } +- +- (*dev)->GetDeviceProduct(dev, &product_id); + if (!product_id) { + debug("%s: ERROR: could not get product id?!\n", __func__); + return NULL; +@@ -3011,6 +3243,17 @@ + SInt32 score; + + while ((device = IOIteratorNext(iterator))) { ++ /* A KIS device's user client is entitlement-gated, so creating the ++ * plug-in fails and it would be dropped here. It's opened through ++ * deviceinterfaced instead. */ ++ if (iokit_registry_pid(device) == KIS_PRODUCT_ID && dic_available()) { ++ struct irecv_iokit_dev_ctx idev; ++ idev.device = device; ++ idev.dev = NULL; ++ _irecv_handle_device_add(&idev); ++ IOObjectRelease(device); ++ continue; ++ } + kr = IOCreatePlugInInterfaceForService(device, kIOUSBDeviceUserClientTypeID, kIOCFPlugInInterfaceID, &plugInInterface, &score); + if ((kIOReturnSuccess != kr) || !plugInInterface) { + debug("%s: ERROR: Unable to create a plug-in (%08x)\n", __func__, kr); diff --git a/crates/restorekit-sys/patches/libirecovery/0002-kis-over-winusb-on-windows.patch b/crates/restorekit-sys/patches/libirecovery/0002-kis-over-winusb-on-windows.patch new file mode 100644 index 0000000..ac9f333 --- /dev/null +++ b/crates/restorekit-sys/patches/libirecovery/0002-kis-over-winusb-on-windows.patch @@ -0,0 +1,328 @@ +--- a/src/libirecovery.c ++++ b/src/libirecovery.c +@@ -55,6 +55,7 @@ + #define WIN32_LEAN_AND_MEAN + #include + #include ++#include + #ifndef sleep + #define sleep(n) Sleep(1000 * n) + #endif +@@ -137,6 +138,7 @@ + #endif + #else + HANDLE handle; ++ WINUSB_INTERFACE_HANDLE kis_winusb; + #endif + irecv_event_cb_t progress_callback; + irecv_event_cb_t received_callback; +@@ -1385,11 +1387,224 @@ + *transferred = count; + } + return ok; ++} ++ ++/* ++ * KIS over WinUSB. The KIS code above talks to Apple's AppleKIS driver, which ++ * does the KIS framing itself behind its own ioctls and shows up as ++ * "\\?\kis#vid_05ac&pid_0001". With plain WinUSB bound to 05ac:1881 instead ++ * (as restorekit does), the device shows up as a regular "\\?\usb#" interface ++ * and has to be spoken to the way the libusb and IOKit backends do: raw KIS ++ * requests on the bulk pipes (CONFIG portal on 0x01/0x81, RSM on 0x03/0x83). ++ * Requests are built as bytes so the layout doesn't depend on the AppleKIS ++ * structs defined for Windows. ++ */ ++#define KISW_HEADER_SIZE 12 ++#define KISW_INFO_SIZE 0x300 ++#define KISW_TRAILER 8 ++#define KISW_CHUNK 0x4000 ++ ++static int kisw_open(irecv_client_t client) ++{ ++ if (!WinUsb_Initialize(client->handle, &client->kis_winusb)) { ++ debug("%s: WinUsb_Initialize failed: %d\n", __func__, (int)GetLastError()); ++ client->kis_winusb = NULL; ++ return 0; ++ } ++ ULONG timeout = USB_TIMEOUT; ++ UCHAR pipes[] = { 0x01, 0x81, 0x03, 0x83 }; ++ for (size_t i = 0; i < sizeof(pipes); i++) { ++ WinUsb_SetPipePolicy(client->kis_winusb, pipes[i], PIPE_TRANSFER_TIMEOUT, sizeof(timeout), &timeout); ++ } ++ return 1; ++} ++ ++static void kisw_put32(uint8_t *p, uint32_t v) ++{ ++ p[0] = v & 0xff; ++ p[1] = (v >> 8) & 0xff; ++ p[2] = (v >> 16) & 0xff; ++ p[3] = (v >> 24) & 0xff; ++} ++ ++static uint32_t kisw_get32(const uint8_t *p) ++{ ++ return p[0] | (p[1] << 8) | (p[2] << 16) | ((uint32_t)p[3] << 24); ++} ++ ++/* Same layout as irecv_kis_request_init. */ ++static void kisw_header(uint8_t *h, uint8_t portal, uint16_t index, size_t arg_count, size_t payload_size, size_t rpl_words) ++{ ++ h[0] = 0; ++ h[1] = 0; ++ h[2] = 0xA0; ++ h[3] = portal; ++ h[4] = (uint8_t)arg_count; ++ h[5] = (uint8_t)(index & 0xFF); ++ h[6] = (uint8_t)(((index >> 8) & 0x3) | ((rpl_words << 2) & 0xFC)); ++ h[7] = (uint8_t)((rpl_words >> 6) & 0xFF); ++ kisw_put32(h + 8, (uint32_t)(payload_size + (arg_count << 2))); ++} ++ ++static irecv_error_t kisw_request(irecv_client_t client, const uint8_t *req, size_t req_size, uint8_t *rpl, size_t *rpl_size) ++{ ++ UCHAR pipe; ++ switch (req[3]) { ++ case KIS_PORTAL_CONFIG: ++ pipe = 0x01; ++ break; ++ case KIS_PORTAL_RSM: ++ pipe = 0x03; ++ break; ++ default: ++ return IRECV_E_INVALID_INPUT; ++ } ++ ULONG sent = 0; ++ if (!WinUsb_WritePipe(client->kis_winusb, pipe, (PUCHAR)req, (ULONG)req_size, &sent, NULL) || sent != req_size) { ++ debug("%s: WinUsb_WritePipe(%#x) failed: %d\n", __func__, pipe, (int)GetLastError()); ++ return IRECV_E_USB_UPLOAD; ++ } ++ ULONG rcvd = 0; ++ if (!WinUsb_ReadPipe(client->kis_winusb, pipe | 0x80, rpl, (ULONG)*rpl_size, &rcvd, NULL)) { ++ debug("%s: WinUsb_ReadPipe(%#x) failed: %d\n", __func__, pipe | 0x80, (int)GetLastError()); ++ return IRECV_E_USB_UPLOAD; ++ } ++ *rpl_size = rcvd; ++ return IRECV_E_SUCCESS; + } ++ ++static irecv_error_t kisw_write32(irecv_client_t client, uint8_t portal, uint16_t index, uint32_t value) ++{ ++ uint8_t req[KISW_HEADER_SIZE + 4]; ++ uint8_t rpl[KISW_HEADER_SIZE + KISW_TRAILER]; ++ size_t rpl_size = sizeof(rpl); ++ kisw_header(req, portal, index, 1, 0, 1); ++ kisw_put32(req + KISW_HEADER_SIZE, value); ++ return kisw_request(client, req, sizeof(req), rpl, &rpl_size); ++} ++ ++static irecv_error_t kisw_init(irecv_client_t client) ++{ ++ irecv_error_t err = kisw_write32(client, KIS_PORTAL_CONFIG, KIS_INDEX_ENABLE_A, KIS_ENABLE_A_VAL); ++ if (err == IRECV_E_SUCCESS) { ++ err = kisw_write32(client, KIS_PORTAL_CONFIG, KIS_INDEX_ENABLE_B, KIS_ENABLE_B_VAL); ++ } ++ if (err != IRECV_E_SUCCESS) { ++ debug("%s: failed to enable KIS device, error %d\n", __func__, err); ++ return err; ++ } ++ client->isKIS = 1; ++ return IRECV_E_SUCCESS; ++} ++ ++/* A USB string descriptor at word offset `word` of the info block, as ASCII. */ ++static int kisw_read_string(const uint8_t *info, uint32_t word, char *buf, size_t buf_size) ++{ ++ size_t off = (size_t)word * 4; ++ if (off + 2 > KISW_INFO_SIZE) { ++ return 0; ++ } ++ uint8_t len = info[off]; ++ if ((len & 1) || info[off + 1] != 3 || len / 2 >= buf_size || off + 2 + len > KISW_INFO_SIZE) { ++ return 0; ++ } ++ for (size_t i = 0; i < len; i += 2) { ++ buf[i / 2] = info[off + 2 + i]; ++ } ++ buf[len / 2] = 0; ++ return len / 2; ++} ++ ++static irecv_error_t kisw_load_device_info(irecv_client_t client) ++{ ++ uint8_t req[KISW_HEADER_SIZE]; ++ uint8_t rpl[KISW_HEADER_SIZE + KISW_INFO_SIZE + KISW_TRAILER]; ++ size_t rpl_size = sizeof(rpl); ++ kisw_header(req, KIS_PORTAL_RSM, KIS_INDEX_GET_INFO, 0, 0, KISW_INFO_SIZE / 4); ++ irecv_error_t err = kisw_request(client, req, sizeof(req), rpl, &rpl_size); ++ if (err != IRECV_E_SUCCESS) { ++ return err; ++ } ++ if (rpl_size < KISW_HEADER_SIZE + KISW_INFO_SIZE) { ++ debug("%s: short GET_INFO reply (%u bytes), not in DFU?\n", __func__, (unsigned)rpl_size); ++ return IRECV_E_INVALID_INPUT; ++ } ++ const uint8_t *info = rpl + KISW_HEADER_SIZE; ++ /* The embedded USB device descriptor starts at 64; iSerialNumber is at +16 ++ * and idProduct at +10. The nonce string's word offset is at 24. */ ++ char buf[0x100]; ++ if (!kisw_read_string(info, info[64 + 16], buf, sizeof(buf))) { ++ return IRECV_E_INVALID_INPUT; ++ } ++ debug("Serial: %s\n", buf); ++ irecv_load_device_info_from_iboot_string(client, buf); ++ if (kisw_read_string(info, kisw_get32(info + 24), buf, sizeof(buf))) { ++ debug("Nonces: %s\n", buf); ++ irecv_copy_nonce_with_tag_from_buffer("NONC", &client->device_info.ap_nonce, &client->device_info.ap_nonce_size, buf); ++ irecv_copy_nonce_with_tag_from_buffer("SNON", &client->device_info.sep_nonce, &client->device_info.sep_nonce_size, buf); ++ } ++ client->mode = info[64 + 10] | (info[64 + 11] << 8); ++ return IRECV_E_SUCCESS; ++} ++ ++static irecv_error_t kisw_send_buffer(irecv_client_t client, unsigned char* buffer, unsigned long length, unsigned int options) ++{ ++ unsigned long orig_len = length; ++ uint64_t address = 0; ++ uint8_t *req = malloc(KISW_HEADER_SIZE + 12 + KISW_CHUNK); ++ if (!req) { ++ return IRECV_E_OUT_OF_MEMORY; ++ } ++ while (length) { ++ size_t chunk = length > KISW_CHUNK ? KISW_CHUNK : length; ++ /* UPLOAD: args are the 64-bit address and the 32-bit size. */ ++ kisw_header(req, KIS_PORTAL_RSM, KIS_INDEX_UPLOAD, 3, chunk, 0); ++ kisw_put32(req + KISW_HEADER_SIZE, (uint32_t)(address & 0xffffffff)); ++ kisw_put32(req + KISW_HEADER_SIZE + 4, (uint32_t)(address >> 32)); ++ kisw_put32(req + KISW_HEADER_SIZE + 8, (uint32_t)chunk); ++ memcpy(req + KISW_HEADER_SIZE + 12, buffer, chunk); ++ ++ uint8_t rpl[KISW_HEADER_SIZE + KISW_TRAILER]; ++ size_t rpl_size = sizeof(rpl); ++ irecv_error_t err = kisw_request(client, req, KISW_HEADER_SIZE + 12 + chunk, rpl, &rpl_size); ++ if (err != IRECV_E_SUCCESS) { ++ free(req); ++ debug("Failed to upload chunk, error %d\n", err); ++ return err; ++ } ++ address += chunk; ++ buffer += chunk; ++ length -= chunk; ++ ++ if (client->progress_callback != NULL) { ++ irecv_event_t event; ++ event.progress = ((double)(orig_len - length) / (double)orig_len) * 100.0; ++ event.type = IRECV_PROGRESS; ++ event.data = (char*)"Uploading"; ++ event.size = orig_len - length; ++ client->progress_callback(client, &event); ++ } ++ } ++ free(req); ++ ++ if (options & IRECV_SEND_OPT_DFU_NOTIFY_FINISH) { ++ irecv_error_t err = kisw_write32(client, KIS_PORTAL_RSM, KIS_INDEX_BOOT_IMG, (uint32_t)orig_len); ++ if (err != IRECV_E_SUCCESS) { ++ debug("Failed to boot image, error %d\n", err); ++ return err; ++ } ++ } ++ return IRECV_E_SUCCESS; ++} + #endif + + static irecv_error_t irecv_kis_init(irecv_client_t client) + { ++#ifdef _WIN32 ++ if (client->kis_winusb) { ++ return kisw_init(client); ++ } ++#endif + #ifdef HAVE_IOKIT + /* deviceinterfaced enables the device itself when it attaches. */ + if (client->kis_dic) { +@@ -1419,6 +1634,11 @@ + { + debug("Loading device info in KIS mode...\n"); + #ifdef _WIN32 ++ if (client->kis_winusb) { ++ return kisw_load_device_info(client); ++ } ++#endif ++#ifdef _WIN32 + KIS_device_info kisInfo; + DWORD transferred = 0; + int ret = win32_device_io_control(client->handle, 0x220004, NULL, 0, &kisInfo, sizeof(kisInfo), &transferred, USB_TIMEOUT); +@@ -1557,11 +1777,13 @@ + if ((guids[k] == &GUID_DEVINTERFACE_DFU && pid != IRECV_K_DFU_MODE && pid != IRECV_K_WTF_MODE) + || (guids[k] == &GUID_DEVINTERFACE_PORTDFU && pid != IRECV_K_PORT_DFU_MODE) + || (guids[k] == &GUID_DEVINTERFACE_IBOOT && (pid < IRECV_K_RECOVERY_MODE_1 || pid > IRECV_K_RECOVERY_MODE_4)) +- || (guids[k] == &GUID_DEVINTERFACE_KIS && pid != 1) ++ || (guids[k] == &GUID_DEVINTERFACE_KIS && pid != 1 && pid != KIS_PRODUCT_ID) + ) { + free(details); + continue; + } ++ /* pid 1 is AppleKIS's own device; 05ac:1881 itself means WinUSB. */ ++ int kis_winusb = (guids[k] == &GUID_DEVINTERFACE_KIS && pid == KIS_PRODUCT_ID); + if (guids[k] == &GUID_DEVINTERFACE_KIS) { + pid = KIS_PRODUCT_ID; + } +@@ -1569,6 +1791,12 @@ + _client->handle = CreateFileA(details->DevicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); + if (_client->handle == INVALID_HANDLE_VALUE) { + debug("%s: Failed to open device path %s: %d\n", __func__, details->DevicePath, (int)GetLastError()); ++ free(details); ++ continue; ++ } ++ if (kis_winusb && !kisw_open(_client)) { ++ CloseHandle(_client->handle); ++ _client->handle = INVALID_HANDLE_VALUE; + free(details); + continue; + } +@@ -2975,6 +3203,12 @@ + free(client); + return NULL; + } ++ /* Not AppleKIS's "kis#" device: WinUSB on 05ac:1881. */ ++ if (strncmp(result, "\\\\?\\kis#", 8) != 0 && !kisw_open(client)) { ++ CloseHandle(client->handle); ++ free(client); ++ return NULL; ++ } + client->mode = pid; + } else { + char* p = strchr(serial_str, '#'); +@@ -3455,7 +3689,7 @@ + if ((guids[k] == &GUID_DEVINTERFACE_DFU && pid != IRECV_K_DFU_MODE && pid != IRECV_K_WTF_MODE) + || (guids[k] == &GUID_DEVINTERFACE_PORTDFU && pid != IRECV_K_PORT_DFU_MODE) + || (guids[k] == &GUID_DEVINTERFACE_IBOOT && (pid < IRECV_K_RECOVERY_MODE_1 || pid > IRECV_K_RECOVERY_MODE_4)) +- || (guids[k] == &GUID_DEVINTERFACE_KIS && pid != 1) ++ || (guids[k] == &GUID_DEVINTERFACE_KIS && pid != 1 && pid != KIS_PRODUCT_ID) + ) { + skip = 1; + } +@@ -3776,6 +4010,10 @@ + } + #endif + #else ++ if (client->kis_winusb) { ++ WinUsb_Free(client->kis_winusb); ++ client->kis_winusb = NULL; ++ } + if (client->handle != NULL && client->handle != INVALID_HANDLE_VALUE) { + CloseHandle(client->handle); + } +@@ -3998,6 +4236,11 @@ + if (client->mode != IRECV_K_DFU_MODE) { + return IRECV_E_UNSUPPORTED; + } ++#ifdef _WIN32 ++ if (client->kis_winusb) { ++ return kisw_send_buffer(client, buffer, length, options); ++ } ++#endif + + unsigned long origLen = length; + diff --git a/crates/restorekit/src/device.rs b/crates/restorekit/src/device.rs index 3d375d8..c88d0cc 100644 --- a/crates/restorekit/src/device.rs +++ b/crates/restorekit/src/device.rs @@ -586,6 +586,8 @@ pub fn model_from_device_version(bcd: u16) -> Option<&'static MacModel> { pub const APPLE_VID: u16 = 0x05ac; /// Product ID presented by an Apple SoC in DFU mode. pub const DFU_PID: u16 = 0x1227; +/// Product ID of a Mac in DFU over Apple's Debug USB interface ("KIS"). +pub const KIS_PID: u16 = 0x1881; /// Product ID presented by a Mac's USB-C controller in Port DFU mode. pub const PORT_DFU_PID: u16 = 0xf014; /// Product ID a Mac's USB-C port controller presents as a USB Billboard device @@ -605,6 +607,11 @@ pub enum UsbMode { /// reconnects in normal SoC DFU mode and the restore continues. #[serde(rename = "port-dfu")] PortDfu, + /// DFU over Apple's Debug USB interface ("KIS", `05ac:1881`): the same + /// bootrom DFU, but the chip identity sits behind a KIS request instead of + /// the USB serial. macOS only lets Apple's own `deviceinterfaced` open it, + /// so on a macOS host the request goes through that daemon. + Kis, /// Recovery mode (iBoot). Recovery, /// WTF ("what's the firmware") mode. @@ -631,6 +638,7 @@ impl UsbMode { match pid { DFU_PID => UsbMode::Dfu, PORT_DFU_PID => UsbMode::PortDfu, + KIS_PID => UsbMode::Kis, 0x1280 | 0x1281 => UsbMode::Recovery, 0x1222 => UsbMode::Wtf, 0x1338 | 0x1339 => UsbMode::Restore, @@ -649,6 +657,7 @@ impl fmt::Display for UsbMode { f.write_str(match self { UsbMode::Dfu => "dfu", UsbMode::PortDfu => "port-dfu", + UsbMode::Kis => "kis", UsbMode::Recovery => "recovery", UsbMode::Wtf => "wtf", UsbMode::Restore => "restore", @@ -684,7 +693,8 @@ pub struct Device { pub mode: UsbMode, /// USB product string, e.g. "Apple Mobile Device (DFU Mode)". pub product: String, - /// Raw USB serial string (empty if the device exposes none). + /// Raw USB serial string (empty if the device exposes none). For a + /// [`UsbMode::Kis`] device, the identity string read over KIS instead. pub serial: String, /// The device's ECID, if known: parsed from the serial in restore modes, or /// filled in for a booted Mac by [`identify`]. @@ -787,15 +797,28 @@ pub struct Port { impl Device { pub fn in_dfu(&self) -> bool { - matches!(self.mode, UsbMode::Dfu | UsbMode::PortDfu) + matches!(self.mode, UsbMode::Dfu | UsbMode::PortDfu | UsbMode::Kis) } - /// Whether restorekit can restore this device right now (normal or Port - /// DFU mode with a readable identity). + /// Whether restorekit can restore this device right now (normal, Port, or + /// KIS DFU mode with a readable identity). pub fn restorable(&self) -> bool { self.in_dfu() && self.identity.is_some() } + /// A Mac in Debug USB DFU whose identity couldn't be read. It's in DFU, but + /// restorekit can't restore it. + pub fn kis_unreadable(&self) -> bool { + self.mode == UsbMode::Kis && self.identity.is_none() + } + + /// A Debug USB (`05ac:1881`) device that isn't in DFU: it answered, but the + /// chip behind it isn't running the boot ROM, so there's no identity. Seen + /// with a booted device whose port was switched to Debug USB over USB-PD. + pub fn debug_usb_not_in_dfu(&self) -> bool { + self.mode == UsbMode::Other && self.usb.pid == KIS_PID + } + /// ECID formatted as idevicerestore expects it (hex with 0x prefix). pub fn ecid_hex(&self) -> Option { self.ecid.map(|e| format!("0x{e:x}")) @@ -923,8 +946,20 @@ fn ecid_from_usb_serial(serial: &str) -> Option { } pub(crate) fn from_usb(info: &nusb::DeviceInfo) -> Device { - let serial = info.serial_number().unwrap_or("").to_string(); - let mode = UsbMode::from_pid(info.product_id()); + let mut mode = UsbMode::from_pid(info.product_id()); + let serial = match mode { + UsbMode::Kis => match crate::kis::identify(info) { + crate::kis::Read::Serial(s) => Some(s), + // Debug USB without DFU behind it isn't a restore mode. + crate::kis::Read::NotInDfu => { + mode = UsbMode::Other; + None + } + crate::kis::Read::Failed => None, + }, + _ => info.serial_number().map(str::to_string), + } + .unwrap_or_default(); let parsed = if mode == UsbMode::PortDfu { parse_port_dfu_serial(&serial) } else { @@ -1534,6 +1569,20 @@ mod tests { assert!(!dev(UsbMode::Recovery, 1).restorable()); } + #[test] + fn kis_mode_is_dfu_and_restorable_once_identified() { + assert_eq!(UsbMode::from_pid(KIS_PID), UsbMode::Kis); + assert_eq!(UsbMode::Kis.to_string(), "kis"); + let mut d = dev(UsbMode::Kis, 3); + assert!(d.in_dfu()); + assert!(d.restorable()); + // A macOS host can't read KIS identity: in DFU, but not restorable. + d.identity = None; + d.ecid = None; + assert!(d.in_dfu()); + assert!(!d.restorable()); + } + #[test] fn select_one_only_matches_dfu() { assert!(select(vec![], Target::One).unwrap().is_none()); diff --git a/crates/restorekit/src/dfu/discovery.rs b/crates/restorekit/src/dfu/discovery.rs index 151c8bd..a509684 100644 --- a/crates/restorekit/src/dfu/discovery.rs +++ b/crates/restorekit/src/dfu/discovery.rs @@ -1,16 +1,8 @@ use std::time::{Duration, Instant}; -use crate::device::{self, Device, APPLE_VID, DFU_PID}; +use crate::device::{self, Device, APPLE_VID, DFU_PID, KIS_PID}; use crate::error::{Error, Result}; -/// The restorable subset of the bus: Macs in DFU mode with a readable identity. -fn restorable() -> Result> { - Ok(device::list()? - .into_iter() - .filter(|d| d.restorable()) - .collect()) -} - /// Watches for a Mac *entering* DFU mode, as opposed to one already there. /// /// Create it with [`watch`] *before* triggering DFU, so the arrival cannot slip @@ -20,6 +12,9 @@ pub struct Watch { events: std::pin::Pin>, /// ECIDs already in DFU when the watch started. already_present: Vec, + /// Unidentified Debug USB (KIS) Macs present when the watch started. They + /// have no ECID to diff on, so count them. + kis_present: usize, } /// Start watching for a Mac to enter DFU mode. See [`Watch`]. @@ -28,10 +23,15 @@ pub fn watch() -> Result { // both queued as an event and in the snapshot, so it is (correctly, since // it predates the caller's DFU trigger) treated as already present. let events = nusb::watch_devices().map_err(Error::from)?; - let already_present = restorable()?.iter().filter_map(|d| d.ecid).collect(); + let devices = device::list()?; Ok(Watch { events: Box::pin(events), - already_present, + already_present: devices + .iter() + .filter(|d| d.restorable()) + .filter_map(|d| d.ecid) + .collect(), + kis_present: devices.iter().filter(|d| d.kis_unreadable()).count(), }) } @@ -49,10 +49,16 @@ impl Watch { // Drain queued hotplug events: the OS telling us a device arrived. while let Some(event) = self.next_event() { if let HotplugEvent::Connected(info) = event { - if info.vendor_id() != APPLE_VID || info.product_id() != DFU_PID { + if info.vendor_id() != APPLE_VID + || !matches!(info.product_id(), DFU_PID | KIS_PID) + { continue; } let dev = device::from_usb(&info); + // A connect event is a new arrival by definition. + if dev.kis_unreadable() { + return Ok(dev); + } if let Some(ecid) = dev.ecid { if !self.already_present.contains(&ecid) { return Ok(dev); @@ -62,10 +68,12 @@ impl Watch { } // Backstop in case a platform's hotplug stream drops an event: // diff the bus against the snapshot. - if let Some(dev) = restorable()? - .into_iter() - .find(|d| d.ecid.is_some_and(|e| !self.already_present.contains(&e))) - { + let devices = device::list()?; + let kis = devices.iter().filter(|d| d.kis_unreadable()).count(); + if let Some(dev) = devices.into_iter().find(|d| { + (d.restorable() && d.ecid.is_some_and(|e| !self.already_present.contains(&e))) + || (d.kis_unreadable() && kis > self.kis_present) + }) { return Ok(dev); } if Instant::now() >= deadline { diff --git a/crates/restorekit/src/dfu/mod.rs b/crates/restorekit/src/dfu/mod.rs index 49e0419..2d2a16c 100644 --- a/crates/restorekit/src/dfu/mod.rs +++ b/crates/restorekit/src/dfu/mod.rs @@ -84,6 +84,27 @@ pub fn probe_ports(progress: crate::progress::ProgressFn) -> crate::error::Resul } } +/// Send one raw USB-PD VDM to the partner on a host DFU port and return the RX +/// VDM register holding the reply. Diagnostic only: the words go out as given. +/// Apple Silicon macOS only, needs root. +pub fn raw_vdm( + target: &DfuTarget, + vdm: &[u32], + progress: crate::progress::ProgressFn, +) -> crate::error::Result<[u8; 64]> { + #[cfg(target_os = "macos")] + { + vdm::raw(target, vdm, progress) + } + #[cfg(not(target_os = "macos"))] + { + let _ = (target, vdm, progress); + Err(crate::error::Error::UnsupportedHost( + "sending VDMs needs an Apple Silicon Mac".into(), + )) + } +} + /// Human label of the host's DFU-capable port (e.g. "left-back"), if the host /// can trigger DFU and the port topology is known. `None` on hosts that can't /// trigger DFU or where the label couldn't be read. diff --git a/crates/restorekit/src/dfu/trigger.rs b/crates/restorekit/src/dfu/trigger.rs index a886e7a..dfd0c21 100644 --- a/crates/restorekit/src/dfu/trigger.rs +++ b/crates/restorekit/src/dfu/trigger.rs @@ -264,7 +264,12 @@ fn wait_entered( want_ecid: Option, timeout: Duration, ) -> Result { - let matches = |d: &Device| d.in_dfu() && want_ecid.is_none_or(|e| d.ecid == Some(e)); + // An unidentified KIS Mac has no ECID to match on; one showing up right + // after we triggered is the target, and re-firing the trigger at a Mac + // already in DFU only fails. + let matches = |d: &Device| { + d.in_dfu() && (d.kis_unreadable() || want_ecid.is_none_or(|e| d.ecid == Some(e))) + }; if let Some(d) = device::list()?.into_iter().find(&matches) { return Ok(d); diff --git a/crates/restorekit/src/dfu/vdm.rs b/crates/restorekit/src/dfu/vdm.rs index 28d9cec..8445896 100644 --- a/crates/restorekit/src/dfu/vdm.rs +++ b/crates/restorekit/src/dfu/vdm.rs @@ -248,6 +248,13 @@ impl Hpm { /// transport failure or a missing reply; an ACK/NAK distinction is left to /// the caller (an Apple action VDM ACKs with `command | 0x40`). fn send_vdm(&self, vdm: &[u32]) -> Result { + let reply = self.send_vdm_raw(vdm)?; + // Reply layout: [status_byte, vdm_header (u32 LE), ...]. + Ok(u32::from_le_bytes([reply[1], reply[2], reply[3], reply[4]])) + } + + /// Send a VDM and return the whole RX VDM register the reply landed in. + fn send_vdm_raw(&self, vdm: &[u32]) -> Result<[u8; 64]> { let start = self.read_register(0x4d)?; let rxst = start[0]; @@ -272,9 +279,7 @@ impl Hpm { if !got { return Err(Error::Vdm("did not get a reply to VDM".into())); } - - // Reply layout: [status_byte, vdm_header (u32 LE), ...]. - Ok(u32::from_le_bytes([reply[1], reply[2], reply[3], reply[4]])) + Ok(reply) } /// Send an Apple action VDM and confirm the target ACKed it (reply @@ -650,6 +655,14 @@ pub fn reboot(target: &DfuTarget, progress: ProgressFn) -> Result<()> { Ok(()) } +/// Send one raw VDM to the partner and return the RX VDM register holding its +/// reply. Diagnostic: the caller picks the words, so this can do anything the +/// partner accepts. +pub fn raw(target: &DfuTarget, vdm: &[u32], progress: ProgressFn) -> Result<[u8; 64]> { + let hpm = connect(target, progress)?; + hpm.send_vdm_raw(vdm) +} + /// Put the cabled target Mac *and* the host's port controller into serial-console /// mode: the target muxes its debug UART onto the USB-C SBU pins and macOS /// exposes it as `/dev/cu.debug-console` (115200 8N1). Port of macvdmtool's diff --git a/crates/restorekit/src/error.rs b/crates/restorekit/src/error.rs index a519aed..6615dd4 100644 --- a/crates/restorekit/src/error.rs +++ b/crates/restorekit/src/error.rs @@ -25,6 +25,9 @@ pub enum Error { #[error("timed out waiting for a Mac to appear in DFU mode")] WaitTimeout, + #[error("{}", kis_unreadable_message())] + KisUnreadable, + #[error("DFU triggering requires an Apple Silicon Mac host running macOS: {0}")] UnsupportedHost(String), @@ -111,6 +114,24 @@ impl From for Error { } } +/// Why a Mac in Debug USB DFU (`05ac:1881`) couldn't be identified, and what to +/// do instead, per host OS. +fn kis_unreadable_message() -> &'static str { + if cfg!(target_os = "macos") { + "the Mac is in DFU over Apple's Debug USB interface (05ac:1881), but restorekit couldn't \ + read its identity through deviceinterfaced. Usually another app has the device open \ + (Chrome, Apple Configurator). Quit it, then put the Mac back into DFU (`restorekit \ + reboot`, then `restorekit dfu`) and retry. macOS only hands the device out when it \ + 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" + } 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" + } +} + /// How to get write access to the USB device nodes, appended to /// [`Error::UsbPermission`]. /// diff --git a/crates/restorekit/src/kis.rs b/crates/restorekit/src/kis.rs new file mode 100644 index 0000000..42d28a0 --- /dev/null +++ b/crates/restorekit/src/kis.rs @@ -0,0 +1,592 @@ +//! Identity of a Mac in DFU over Apple's Debug USB interface ("KIS", `05ac:1881`). +//! +//! A KIS-mode Mac is in the same bootrom DFU as a classic `05ac:1227` one, but its +//! USB serial is empty: the `CPID:… BDID:… ECID:…` string sits behind a KIS +//! request instead. This is a port of libirecovery's `irecv_kis_init` + +//! `irecv_kis_load_device_info` over nusb, so we can open exactly the device we +//! enumerated (libirecovery's `irecv_open_with_ecid(0)` takes whichever +//! restore-family device it finds first). +//! +//! macOS gates `05ac:1881` behind the `com.apple.private.debug-usb.access` +//! entitlement, which only Apple's `deviceinterfaced` holds. The daemon hands a +//! raw KIS transport to any client through the private +//! `DeviceInterfaceClient.framework`, so on macOS the same request goes through +//! it instead (see [`dic`]). The vendored libirecovery is patched the same way +//! for the restore itself (`restorekit-sys/patches/libirecovery`). + +use std::collections::HashMap; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +#[cfg(not(target_os = "macos"))] +use nusb::transfer::{Buffer, Bulk, In, Out}; +use nusb::MaybeFuture; + +#[cfg_attr(target_os = "macos", allow(dead_code))] +const PORTAL_CONFIG: u8 = 0x01; +const PORTAL_RSM: u8 = 0x10; + +#[cfg_attr(target_os = "macos", allow(dead_code))] +const INDEX_ENABLE_A: u16 = 0x0a; +#[cfg_attr(target_os = "macos", allow(dead_code))] +const INDEX_ENABLE_B: u16 = 0x14; +const INDEX_GET_INFO: u16 = 0x100; +#[cfg_attr(target_os = "macos", allow(dead_code))] +const ENABLE_A: u32 = 0x21; +#[cfg_attr(target_os = "macos", allow(dead_code))] +const ENABLE_B: u32 = 0x01; + +const HEADER_LEN: usize = 12; +/// Size of the device-info block the GET_INFO reply carries after its header. +const INFO_LEN: usize = 0x300; +/// Offset of the embedded USB device descriptor inside the info block. +const DESCRIPTOR_OFFSET: usize = 64; +/// `iSerialNumber` within a USB device descriptor. +const I_SERIAL_NUMBER: usize = 16; +/// Word offset of the nonce string, inside the info block. +const NONCE_OFFSET: usize = 24; + +#[cfg_attr(target_os = "macos", allow(dead_code))] +const TIMEOUT: Duration = Duration::from_secs(2); + +/// What a Debug USB device answered to GET_INFO. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum Read { + /// In DFU: the identity string (`CPID:… ECID:…`). + Serial(String), + /// It answered, but with no info block: the chip isn't in DFU (e.g. a + /// booted device with Debug USB switched on at its port), so there's no + /// identity to read. + NotInDfu, + /// The request itself failed. + Failed, +} + +/// How long after a KIS device first shows up a failed read is retried right +/// away. On macOS `deviceinterfaced` attaches to the device on the same +/// arrival, so the first request can land before it's ready. +const ARRIVAL_GRACE: Duration = Duration::from_secs(3); + +/// 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 first_seen = { + let mut seen = seen.lock().unwrap(); + let entry = seen.entry(info.id()).or_insert((Instant::now(), None)); + if let Some(serial) = &entry.1 { + return Read::Serial(serial.clone()); + } + entry.0 + }; + let read = loop { + let read = read(info); + if read != Read::Failed || first_seen.elapsed() >= ARRIVAL_GRACE { + break read; + } + std::thread::sleep(Duration::from_millis(250)); + }; + if let Read::Serial(serial) = &read { + seen.lock() + .unwrap() + .insert(info.id(), (first_seen, Some(serial.clone()))); + } + read +} + +fn read(info: &nusb::DeviceInfo) -> Read { + match get_info(info) { + Ok(reply) => classify(&reply), + Err(_) => Read::Failed, + } +} + +/// A full reply carries the 0x300-byte info block; a short one (just the +/// header and the size/status trailer) means the device has none to give. +fn classify(reply: &[u8]) -> Read { + if reply.len() < HEADER_LEN + INFO_LEN { + return Read::NotInDfu; + } + match serial_from_info(&reply[HEADER_LEN..]) { + Some(serial) => Read::Serial(serial), + None => Read::Failed, + } +} + +/// The raw GET_INFO reply (header, info block, trailer) for the device. +#[cfg(not(target_os = "macos"))] +fn get_info(info: &nusb::DeviceInfo) -> Result, String> { + let dev = info.open().wait().map_err(|e| format!("open: {e}"))?; + let iface = dev + .claim_interface(0) + .wait() + .map_err(|e| format!("claim interface 0: {e}"))?; + let mut config = Portal::open(&iface, 0x01).ok_or("open EP 0x01/0x81")?; + let mut rsm = Portal::open(&iface, 0x03).ok_or("open EP 0x03/0x83")?; + config + .request(PORTAL_CONFIG, INDEX_ENABLE_A, &[ENABLE_A], 1) + .ok_or("config write 0x0a")?; + config + .request(PORTAL_CONFIG, INDEX_ENABLE_B, &[ENABLE_B], 1) + .ok_or("config write 0x14")?; + rsm.request(PORTAL_RSM, INDEX_GET_INFO, &[], INFO_LEN / 4) + .ok_or_else(|| "GET_INFO".to_string()) +} + +/// The raw GET_INFO reply, through `deviceinterfaced`. It enables the device +/// itself when it attaches, so there's no config write here. +#[cfg(target_os = "macos")] +fn get_info(info: &nusb::DeviceInfo) -> Result, String> { + let id = dic::interface_for(info.registry_entry_id())?; + let req = header(PORTAL_RSM, INDEX_GET_INFO, 0, INFO_LEN / 4); + dic::request(id, &req, HEADER_LEN + INFO_LEN + 8) +} + +/// A readable dump of every KIS device on the bus: what `deviceinterfaced` sees +/// (macOS), the raw GET_INFO reply and what it parses to. For checking the +/// transport on real hardware; prints nothing it can't read rather than failing. +pub fn probe() -> String { + use std::fmt::Write; + let mut out = String::new(); + #[cfg(target_os = "macos")] + dic::describe(&mut out); + let devices: Vec<_> = match nusb::list_devices().wait() { + Ok(d) => d + .filter(|d| { + d.vendor_id() == crate::device::APPLE_VID + && d.product_id() == crate::device::KIS_PID + }) + .collect(), + Err(e) => { + let _ = writeln!(out, "list USB devices: {e}"); + return out; + } + }; + if devices.is_empty() { + let _ = writeln!(out, "no 05ac:1881 device on the bus"); + } + for info in &devices { + let _ = writeln!(out, "\n05ac:1881 {:?}", info.id()); + #[cfg(target_os = "macos")] + let _ = writeln!(out, " registry entry id {:#x}", info.registry_entry_id()); + match get_info(info) { + Ok(reply) => { + let _ = writeln!(out, " GET_INFO reply, {} bytes:", reply.len()); + hexdump(&mut out, &reply); + let body = reply.get(HEADER_LEN..).unwrap_or_default(); + let _ = writeln!(out, " reads as: {:?}", classify(&reply)); + let _ = writeln!(out, " serial: {:?}", serial_from_info(body)); + let _ = writeln!(out, " nonces: {:?}", nonces_from_info(body)); + } + Err(e) => { + let _ = writeln!(out, " GET_INFO failed: {e}"); + } + } + } + out +} + +fn hexdump(out: &mut String, bytes: &[u8]) { + use std::fmt::Write; + for (i, row) in bytes.chunks(16).enumerate() { + let hex: Vec = row.iter().map(|b| format!("{b:02x}")).collect(); + let text: String = row + .iter() + .map(|&b| { + if (0x20..0x7f).contains(&b) { + b as char + } else { + '.' + } + }) + .collect(); + let _ = writeln!(out, " {:04x}: {:<47} {text}", i * 16, hex.join(" ")); + } +} + +/// A KIS portal: a bulk OUT/IN endpoint pair. +#[cfg(not(target_os = "macos"))] +struct Portal { + out: nusb::Endpoint, + inp: nusb::Endpoint, +} + +#[cfg(not(target_os = "macos"))] +impl Portal { + fn open(iface: &nusb::Interface, ep: u8) -> Option { + Some(Portal { + out: iface.endpoint::(ep).ok()?, + inp: iface.endpoint::(ep | 0x80).ok()?, + }) + } + + fn request( + &mut self, + portal: u8, + index: u16, + args: &[u32], + reply_words: usize, + ) -> Option> { + let mut req = header(portal, index, args.len(), reply_words).to_vec(); + for a in args { + req.extend_from_slice(&a.to_le_bytes()); + } + self.out + .transfer_blocking(req.into(), TIMEOUT) + .status + .ok()?; + // Reply: header, payload words, then a size/status trailer. IN transfers + // must be a whole number of max-size packets. + let mps = self.inp.max_packet_size().max(1); + let want = (HEADER_LEN + reply_words * 4 + 8).div_ceil(mps) * mps; + let done = self.inp.transfer_blocking(Buffer::new(want), TIMEOUT); + done.status.ok()?; + Some(done.buffer.into_vec()) + } +} + +/// The 12-byte KIS request header (libirecovery's `irecv_kis_request_init`). +fn header(portal: u8, index: u16, arg_count: usize, reply_words: usize) -> [u8; HEADER_LEN] { + let req_size = (arg_count * 4) as u32; + let mut h = [0u8; HEADER_LEN]; + // h[0..2]: sequence number, ignored by the device. + h[2] = 0xa0; // protocol version + h[3] = portal; + h[4] = arg_count as u8; + h[5] = (index & 0xff) as u8; + h[6] = (((index >> 8) & 0x3) as u8) | (((reply_words << 2) & 0xfc) as u8); + h[7] = ((reply_words >> 6) & 0xff) as u8; + h[8..12].copy_from_slice(&req_size.to_le_bytes()); + h +} + +/// Pull the serial string out of a GET_INFO info block: the embedded device +/// descriptor's `iSerialNumber` is a word offset to a USB string descriptor. +fn serial_from_info(info: &[u8]) -> Option { + let index = *info.get(DESCRIPTOR_OFFSET + I_SERIAL_NUMBER)? as usize; + string_at(info, index * 4) +} + +/// The `NONC:… SNON:…` string, at the word offset stored at `NONCE_OFFSET`. +fn nonces_from_info(info: &[u8]) -> Option { + let word = u32::from_le_bytes(info.get(NONCE_OFFSET..NONCE_OFFSET + 4)?.try_into().ok()?); + string_at(info, word as usize * 4) +} + +/// A USB string descriptor (`bLength`, `bDescriptorType` = 3, UTF-16LE) at `off`. +fn string_at(info: &[u8], off: usize) -> Option { + let len = *info.get(off)? as usize; + if *info.get(off + 1)? != 3 || !len.is_multiple_of(2) { + return None; + } + let units: Vec = info + .get(off + 2..off + 2 + len)? + .as_chunks::<2>() + .0 + .iter() + .map(|c| u16::from_le_bytes(*c)) + .collect(); + let s = String::from_utf16(&units).ok()?; + (!s.is_empty()).then_some(s) +} + +/// The KIS transport `deviceinterfaced` exposes through +/// `DeviceInterfaceClient.framework`. The framework is private and undocumented; +/// these signatures come from disassembling it and were checked against a live +/// Debug USB device (an iPhone with Debug USB enabled over USB-PD): listing, +/// portal-to-endpoint mapping and a GET_INFO round trip. +#[cfg(target_os = "macos")] +mod dic { + use std::ffi::{c_char, c_void, CStr}; + use std::fmt::Write; + use std::sync::atomic::{AtomicU16, Ordering}; + use std::sync::OnceLock; + + const FRAMEWORK: &CStr = c"/Library/Apple/System/Library/PrivateFrameworks/DeviceInterfaceClient.framework/DeviceInterfaceClient"; + const TADFU_FRAMEWORK: &CStr = + c"/Library/Apple/System/Library/PrivateFrameworks/DeviceInterface.framework/DeviceInterface"; + const TIMEOUT_MS: u64 = 2000; + + type Create = unsafe extern "C" fn(*mut c_void) -> *mut c_void; + type List = unsafe extern "C" fn(*mut c_void, *mut u64, *mut usize) -> bool; + type Transfer = unsafe extern "C" fn( + *mut c_void, + u64, + *const u64, + u32, + *const c_void, + usize, + *mut c_void, + *mut usize, + ) -> bool; + + extern "C" { + fn dispatch_queue_create(label: *const c_char, attr: *mut c_void) -> *mut c_void; + } + + struct Client { + handle: *mut c_void, + list: List, + transfer: Transfer, + } + // The framework's client is an XPC connection wrapper, safe across threads. + unsafe impl Send for Client {} + unsafe impl Sync for Client {} + + fn client() -> Result<&'static Client, String> { + static CLIENT: OnceLock> = OnceLock::new(); + CLIENT + .get_or_init(|| unsafe { + let h = libc::dlopen(FRAMEWORK.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL); + if h.is_null() { + return Err("DeviceInterfaceClient.framework not found".into()); + } + let sym = |name: &CStr| libc::dlsym(h, name.as_ptr()); + let create = sym(c"device_interface_client_server_xpc_client_create"); + let list = sym(c"device_interface_client_server_xpc_client_list_devices"); + let transfer = sym(c"device_interface_client_server_xpc_client_transfer_data"); + if create.is_null() || list.is_null() || transfer.is_null() { + return Err( + "DeviceInterfaceClient.framework is missing expected symbols".into(), + ); + } + let create: Create = std::mem::transmute(create); + let queue = dispatch_queue_create(c"restorekit.kis".as_ptr(), std::ptr::null_mut()); + let handle = create(queue); + if handle.is_null() { + return Err("could not connect to deviceinterfaced".into()); + } + Ok(Client { + handle, + list: std::mem::transmute::<*mut c_void, List>(list), + transfer: std::mem::transmute::<*mut c_void, Transfer>(transfer), + }) + }) + .as_ref() + .map_err(Clone::clone) + } + + fn interfaces() -> Result, String> { + let c = client()?; + let mut ids = [0u64; 16]; + let mut count = ids.len(); + if !unsafe { (c.list)(c.handle, ids.as_mut_ptr(), &mut count) } { + return Err("deviceinterfaced list_devices failed".into()); + } + Ok(ids[..count.min(ids.len())].to_vec()) + } + + #[link(name = "IOKit", kind = "framework")] + extern "C" { + fn IORegistryEntryIDMatching(id: u64) -> *const c_void; + fn IOServiceGetMatchingService(main_port: u32, matching: *const c_void) -> u32; + fn IORegistryEntryGetParentEntry(entry: u32, plane: *const c_char, parent: *mut u32) + -> i32; + fn IORegistryEntryGetRegistryEntryID(entry: u32, id: *mut u64) -> i32; + fn IOObjectRelease(object: u32) -> i32; + } + + /// Registry entry id of the parent (IOService plane) of the entry `id`. + fn parent_id(id: u64) -> Option { + unsafe { + let entry = IOServiceGetMatchingService(0, IORegistryEntryIDMatching(id)); + if entry == 0 { + return None; + } + let mut parent = 0; + let kr = IORegistryEntryGetParentEntry(entry, c"IOService".as_ptr(), &mut parent); + IOObjectRelease(entry); + if kr != 0 { + return None; + } + let mut pid = 0; + let kr = IORegistryEntryGetRegistryEntryID(parent, &mut pid); + IOObjectRelease(parent); + (kr == 0).then_some(pid) + } + } + + /// The daemon's interface id for the device with this registry entry id. + /// The ids are registry entry ids of the device's `IOUSBHostInterface` + /// (seen on a live Debug USB device), so match on the parent; failing + /// that, a lone interface can only be this device. + pub fn interface_for(registry_id: u64) -> Result { + let ids = interfaces()?; + if let Some(id) = ids.iter().find(|&&id| parent_id(id) == Some(registry_id)) { + return Ok(*id); + } + match ids.as_slice() { + [id] => Ok(*id), + [] => Err("deviceinterfaced lists no KIS interfaces".into()), + _ => Err(format!( + "{} KIS interfaces and none match this device", + ids.len() + )), + } + } + + /// Send one KIS request (12-byte header, args, payload) and return the raw + /// reply. The daemon writes `scalars[1..]` out as little-endian u32 words + /// followed by the input bytes, so the header goes in as scalars. + pub fn request(id: u64, req: &[u8], reply_cap: usize) -> Result, String> { + let c = client()?; + // Replies are matched by the first header word and the daemon uses + // 0xFFxx itself; the patched libirecovery uses 1..0x8000. + static SEQ: AtomicU16 = AtomicU16::new(0); + let seq = 0x8000 + SEQ.fetch_add(1, Ordering::Relaxed) % 0x7f00; + let mut req = req.to_vec(); + req[..2].copy_from_slice(&seq.to_le_bytes()); + + let words = (3 + req[4] as usize).min(15).min(req.len() / 4); + let mut scalars = vec![TIMEOUT_MS]; + scalars.extend( + req[..words * 4] + .as_chunks::<4>() + .0 + .iter() + .map(|w| u32::from_le_bytes(*w) as u64), + ); + let payload = &req[words * 4..]; + let mut out = vec![0u8; reply_cap]; + let mut out_len = out.len(); + let ok = unsafe { + (c.transfer)( + c.handle, + id, + scalars.as_ptr(), + scalars.len() as u32, + if payload.is_empty() { + std::ptr::null() + } else { + payload.as_ptr().cast() + }, + payload.len(), + out.as_mut_ptr().cast(), + &mut out_len, + ) + }; + if !ok { + return Err("deviceinterfaced transfer_data failed".into()); + } + out.truncate(out_len); + Ok(out) + } + + /// What the daemon reports: its KIS interfaces and TADFU devices. + pub fn describe(out: &mut String) { + match interfaces() { + Ok(ids) => { + let ids: Vec = ids + .iter() + .map(|&i| match parent_id(i) { + Some(p) => format!("{i:#x} (on device {p:#x})"), + None => format!("{i:#x}"), + }) + .collect(); + let _ = writeln!(out, "deviceinterfaced KIS interfaces: [{}]", ids.join(", ")); + } + Err(e) => { + let _ = writeln!(out, "deviceinterfaced: {e}"); + } + } + let _ = writeln!(out, "TADFU devices: {}", tadfu_devices()); + } + + /// `tadfu_transport_client_copy_all_devices_information`, described. This is + /// the higher-level path Apple's MobileDevice uses for KIS restores; dumped + /// so a hardware test shows what it offers if the raw path falls short. + fn tadfu_devices() -> String { + use core_foundation::base::{CFType, TCFType}; + type Cb = unsafe extern "C" fn(*const c_void, *mut c_void); + type Create = unsafe extern "C" fn(Cb, *mut c_void, Cb, *mut c_void) -> *mut c_void; + type Copy = unsafe extern "C" fn(*mut c_void) -> *const c_void; + unsafe extern "C" fn ignore(_: *const c_void, _: *mut c_void) {} + unsafe { + let h = libc::dlopen(TADFU_FRAMEWORK.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL); + if h.is_null() { + return "DeviceInterface.framework not found".into(); + } + let create = libc::dlsym( + h, + c"tadfu_transport_client_create_with_device_discovery_callbacks".as_ptr(), + ); + let copy = libc::dlsym( + h, + c"tadfu_transport_client_copy_all_devices_information".as_ptr(), + ); + if create.is_null() || copy.is_null() { + return "DeviceInterface.framework is missing expected symbols".into(); + } + let create: Create = std::mem::transmute(create); + let copy: Copy = std::mem::transmute(copy); + let client = create(ignore, std::ptr::null_mut(), ignore, std::ptr::null_mut()); + if client.is_null() { + return "could not connect to the TADFU server".into(); + } + // Discovery is asynchronous; give the initial device list a moment. + std::thread::sleep(std::time::Duration::from_millis(500)); + let all = copy(client); + if all.is_null() { + return "none".into(); + } + format!("{:?}", CFType::wrap_under_create_rule(all as _)) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn header_matches_libirecovery() { + // GET_INFO on the RSM portal, 0xC0 reply words, no args. + assert_eq!( + header(PORTAL_RSM, INDEX_GET_INFO, 0, INFO_LEN / 4), + [0, 0, 0xa0, 0x10, 0, 0x00, 0x01, 0x03, 0, 0, 0, 0] + ); + // Config write: one arg, one reply word. + assert_eq!( + header(PORTAL_CONFIG, INDEX_ENABLE_A, 1, 1), + [0, 0, 0xa0, 0x01, 1, 0x0a, 0x04, 0x00, 4, 0, 0, 0] + ); + } + + #[test] + fn parses_serial_from_info_block() { + let serial = "CPID:8142 CPRV:01 BDID:0E ECID:001A2B3C4D5E6F70"; + let mut info = vec![0u8; INFO_LEN]; + let word = 0x40; // string at byte 0x100 + info[DESCRIPTOR_OFFSET + I_SERIAL_NUMBER] = word as u8; + let off = word * 4; + let utf16: Vec = serial.encode_utf16().flat_map(u16::to_le_bytes).collect(); + info[off] = utf16.len() as u8; + info[off + 1] = 3; + info[off + 2..off + 2 + utf16.len()].copy_from_slice(&utf16); + assert_eq!(serial_from_info(&info).as_deref(), Some(serial)); + } + + #[test] + fn short_reply_means_not_in_dfu() { + // What a booted iPhone with Debug USB on answered: header + trailer. + let reply = [ + 0x00, 0x80, 0xa0, 0x10, 0, 0x01, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]; + assert_eq!(classify(&reply), Read::NotInDfu); + assert_eq!(classify(&[0u8; HEADER_LEN + INFO_LEN + 8]), Read::Failed); + } + + #[test] + fn rejects_non_string_descriptor() { + let mut info = vec![0u8; INFO_LEN]; + info[DESCRIPTOR_OFFSET + I_SERIAL_NUMBER] = 0x40; + info[0x100] = 4; + info[0x101] = 1; + assert!(serial_from_info(&info).is_none()); + } +} diff --git a/crates/restorekit/src/lib.rs b/crates/restorekit/src/lib.rs index af5cc72..668b7c1 100644 --- a/crates/restorekit/src/lib.rs +++ b/crates/restorekit/src/lib.rs @@ -69,6 +69,8 @@ pub mod error; pub mod firmware; #[cfg(feature = "history")] pub mod history; +#[doc(hidden)] +pub mod kis; pub mod progress; pub mod restore; #[cfg(any(target_os = "linux", target_os = "windows"))] diff --git a/udev/51-restorekit.rules b/udev/51-restorekit.rules index 67401ad..f604c1c 100644 --- a/udev/51-restorekit.rules +++ b/udev/51-restorekit.rules @@ -24,3 +24,6 @@ ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="05ac", ATTR{idProduct}=="8600" ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="05ac", ATTR{idProduct}=="122[27]", MODE="0666" ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="05ac", ATTR{idProduct}=="128[0-3]", MODE="0666" ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="05ac", ATTR{idProduct}=="1338", MODE="0666" + +# DFU over Debug USB ("KIS", PID 0x1881) +ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="05ac", ATTR{idProduct}=="1881", MODE="0666"