Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
82da699225 | ||
|
|
1adc8a59ce | ||
|
|
6a1f03f862 | ||
|
|
db0c7395f1 | ||
|
|
1bac132e21 | ||
|
|
d3ceaeaa0b | ||
|
|
914debd758 |
No files matched your search
Generated
+3
-3
@@ -213,7 +213,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
[[package]]
|
||||
name = "metal2vulkan"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/reims-go/metal2vulkan?rev=7b3aedb5fa6aed2df5ea6397a6624f16270db183#7b3aedb5fa6aed2df5ea6397a6624f16270db183"
|
||||
source = "git+https://github.com/reims-go/metal2vulkan?rev=1dd4e970c0562c73bd3eba12cd15999bb035e019#1dd4e970c0562c73bd3eba12cd15999bb035e019"
|
||||
dependencies = [
|
||||
"ash",
|
||||
"metal2vulkan-air",
|
||||
@@ -224,7 +224,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "metal2vulkan-air"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/reims-go/metal2vulkan?rev=7b3aedb5fa6aed2df5ea6397a6624f16270db183#7b3aedb5fa6aed2df5ea6397a6624f16270db183"
|
||||
source = "git+https://github.com/reims-go/metal2vulkan?rev=1dd4e970c0562c73bd3eba12cd15999bb035e019#1dd4e970c0562c73bd3eba12cd15999bb035e019"
|
||||
dependencies = [
|
||||
"sha2 0.11.1",
|
||||
]
|
||||
@@ -232,7 +232,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "metal2vulkan-runtime"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/reims-go/metal2vulkan?rev=7b3aedb5fa6aed2df5ea6397a6624f16270db183#7b3aedb5fa6aed2df5ea6397a6624f16270db183"
|
||||
source = "git+https://github.com/reims-go/metal2vulkan?rev=1dd4e970c0562c73bd3eba12cd15999bb035e019#1dd4e970c0562c73bd3eba12cd15999bb035e019"
|
||||
dependencies = [
|
||||
"ash",
|
||||
"libc",
|
||||
|
||||
+2
-2
@@ -33,11 +33,11 @@ reims-vgpu-graphics = { path = "crates/reims-vgpu-graphics" }
|
||||
reims-vgpu-video = { path = "crates/reims-vgpu-video" }
|
||||
# metal2vulkan's Metal types, for the Metal enums and descriptor values the runtime's calls take,
|
||||
# from metal2vulkan's public repository at the commit both name.
|
||||
metal2vulkan = { git = "https://github.com/reims-go/metal2vulkan", rev = "7b3aedb5fa6aed2df5ea6397a6624f16270db183" }
|
||||
metal2vulkan = { git = "https://github.com/reims-go/metal2vulkan", rev = "1dd4e970c0562c73bd3eba12cd15999bb035e019" }
|
||||
# The Vulkan platform's runtime (architecture D1), metal2vulkan-runtime: a Metal-shaped API on
|
||||
# Vulkan, one path for every device, under reims-vgpu-vulkan's `rt_platform` and `seam` and
|
||||
# reims-vgpu's `pool::rt_blocks`.
|
||||
metal2vulkan-runtime = { git = "https://github.com/reims-go/metal2vulkan", rev = "7b3aedb5fa6aed2df5ea6397a6624f16270db183" }
|
||||
metal2vulkan-runtime = { git = "https://github.com/reims-go/metal2vulkan", rev = "1dd4e970c0562c73bd3eba12cd15999bb035e019" }
|
||||
# The hashes of the Vulkan platform's metallib sources (reims-vgpu-vulkan/build.rs).
|
||||
sha2 = "0.10.9"
|
||||
# A display window's swapchain on Linux (reims-vgpu-vulkan/src/swapchain.rs), at the runtime's
|
||||
|
||||
@@ -1322,6 +1322,8 @@ reims-ctl attaches nothing through it yet: no VM it starts has a
|
||||
`usb-redir` device. The build gets the parser from MSYS2's
|
||||
`mingw-w64-clang-x86_64-usbredir` package, and the install stops where the
|
||||
QEMU it staged lists no `usb-redir` device.
|
||||
The standalone [Windows iPad Air M3 enumeration helper](windows-ipad-air-m3.md)
|
||||
uses this device in a running x86-64 macOS guest.
|
||||
|
||||
With `REIMS_INSTALL_SKIP_HOST_CHECKS=1` in its environment, install.ps1
|
||||
skips the hypervisor platform's step, its check and its turning on, and
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# Enumerate an iPad Air M3 over USB on Windows
|
||||
|
||||
This experimental source helper exposes one iPad Air M3 to a running x86-64
|
||||
macOS Reims guest on Windows. It checks for USB ID `05ac:12ab`, device
|
||||
revision `1503`, and the initial four-configuration layout. The session
|
||||
ends when the device changes its USB address. The first enumeration is the
|
||||
test target. Reattaching after Apple's mode change and Xcode are pending.
|
||||
|
||||
## Prepare the guest and host
|
||||
|
||||
- Start the guest with a Windows QEMU build that lists `usb-redir` in
|
||||
`-device help`. The guest must have the standard `xhci` controller.
|
||||
- Use 64-bit PowerShell 7, 64-bit Python 3.10 or later with PyUSB 1.3.1, and
|
||||
Go to build the local QMP relay.
|
||||
- Download and extract the signed [libusb-win32 1.4.0.2 binary
|
||||
release](https://github.com/mcuee/libusb-win32/releases/tag/release_1.4.0.2).
|
||||
The `bin/amd64` directory contains the matching SYS and DLL files.
|
||||
The helper checks their hashes before use.
|
||||
- Connect just one unlocked iPad in normal mode. Windows must already
|
||||
recognize it, and the device must be unshared by usbipd-win.
|
||||
|
||||
From the repository root, in an ordinary PowerShell window:
|
||||
|
||||
```powershell
|
||||
py -3 -m venv .\build\windows-ipad-air-m3\venv
|
||||
.\build\windows-ipad-air-m3\venv\Scripts\python.exe -m pip install PyUSB==1.3.1
|
||||
go build -o .\build\windows-ipad-air-m3\qmp-relay.exe .\scripts\windows-ipad-air-m3\qmp-relay.go
|
||||
.\build\windows-ipad-air-m3\venv\Scripts\python.exe .\scripts\windows-ipad-air-m3\attach.py `
|
||||
--vm-dir 'C:\path\to\vm' `
|
||||
--relay .\build\windows-ipad-air-m3\qmp-relay.exe `
|
||||
--driver-dir 'C:\path\to\libusb-win32\bin\amd64'
|
||||
```
|
||||
|
||||
The VM directory is the one shown by `reims-ctl list`. Use `--qmp` if
|
||||
the running guest's QMP socket lives outside that directory.
|
||||
|
||||
Approve Windows elevation for the temporary filter. When prompted, unplug
|
||||
the iPad, wait two seconds and plug it back into the same port. The
|
||||
terminal reports when the guest reads the USB device descriptor. When it
|
||||
requests a final unplug, leave the iPad disconnected until it confirms
|
||||
Windows restoration. If an interrupted session reports pending recovery,
|
||||
unplug the iPad and run
|
||||
`pwsh -File .\scripts\windows-ipad-air-m3\driver-session.ps1 -Recover`
|
||||
from an elevated PowerShell 7 window before reconnecting.
|
||||
|
||||
The driver transaction, USB access and forwarding protocol are adapted from
|
||||
[MonchiLin's Windows iPad contribution](https://github.com/MonchiLin/reims-vgpu/tree/5e69f1ba9d0f0267a670a1fb836b794184ec36bf/scripts/windows-ipad)
|
||||
under this repository's [dual license](../LICENSE).
|
||||
@@ -0,0 +1,276 @@
|
||||
"""Enumerate an iPad Air M3 in a running Windows Reims guest."""
|
||||
import argparse
|
||||
from contextlib import closing, contextmanager
|
||||
import json
|
||||
from pathlib import Path
|
||||
from queue import Empty, Queue
|
||||
from secrets import token_hex
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
from threading import Event, Thread
|
||||
from time import monotonic, sleep
|
||||
|
||||
from driver_pipe import driver_session, peer_is_qemu
|
||||
from usb_device import IPAD, REVISION, Ipad, backend_from
|
||||
from usb_hub import Hub
|
||||
import usb_redir
|
||||
|
||||
|
||||
class Monitor:
|
||||
def __init__(self, process):
|
||||
self.process = process
|
||||
if "QMP" not in self.read():
|
||||
raise RuntimeError("QEMU did not send a QMP greeting")
|
||||
self.call("qmp_capabilities")
|
||||
|
||||
def read(self):
|
||||
line = self.process.stdout.readline()
|
||||
if not line:
|
||||
raise RuntimeError("QEMU closed the monitor connection")
|
||||
return json.loads(line)
|
||||
|
||||
def call(self, command, **arguments):
|
||||
packet = {"execute": command}
|
||||
if arguments:
|
||||
packet["arguments"] = arguments
|
||||
self.process.stdin.write(json.dumps(packet).encode() + b"\n")
|
||||
self.process.stdin.flush()
|
||||
while True:
|
||||
answer = self.read()
|
||||
if "event" in answer:
|
||||
continue
|
||||
if "error" in answer:
|
||||
raise RuntimeError(f"{command}: {answer['error']['desc']}")
|
||||
return answer["return"]
|
||||
|
||||
|
||||
class Guest:
|
||||
def __init__(self, directory, qmp_path, relay):
|
||||
self.pid_file = directory / "qemu.pid"
|
||||
self.pid = self.current_pid()
|
||||
if self.pid is None:
|
||||
raise ValueError("The VM has no valid QEMU PID")
|
||||
self.qmp_path = qmp_path
|
||||
self.relay = relay
|
||||
|
||||
def current_pid(self):
|
||||
try:
|
||||
pid = int(self.pid_file.read_text().strip())
|
||||
return pid if pid > 0 else None
|
||||
except (FileNotFoundError, ValueError):
|
||||
return None
|
||||
|
||||
@contextmanager
|
||||
def monitor(self):
|
||||
if self.current_pid() != self.pid:
|
||||
raise RuntimeError("The VM stopped or restarted during the session")
|
||||
with subprocess.Popen([str(self.relay), str(self.qmp_path)], stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE, creationflags=subprocess.CREATE_NO_WINDOW) as process:
|
||||
try:
|
||||
monitor = Monitor(process)
|
||||
if self.current_pid() != self.pid:
|
||||
raise RuntimeError("The VM restarted before the monitor opened")
|
||||
yield monitor
|
||||
finally:
|
||||
process.stdin.close()
|
||||
|
||||
|
||||
class MeasuredIpad(Ipad):
|
||||
def __init__(self, backend, info, superspeed):
|
||||
super().__init__(backend, info)
|
||||
self.speed = 3 if superspeed else self.speed
|
||||
self.descriptor_read = False
|
||||
self.mode_request_seen = False
|
||||
|
||||
def control(self, setup, data):
|
||||
kind, request, value, index, _ = setup
|
||||
if (kind, request) == (0xC0, 0x52) and not self.mode_request_seen:
|
||||
self.mode_request_seen = True
|
||||
print(f"The guest requested Apple USB mode {index}.", flush=True)
|
||||
reply = super().control(setup, data)
|
||||
if (kind, request, value) == (0x80, 6, 0x0100) and len(reply) >= 18:
|
||||
if struct.unpack_from("<HHH", reply, 8) == (*IPAD, REVISION) and not self.descriptor_read:
|
||||
self.descriptor_read = True
|
||||
print("The guest read the iPad Air M3 USB device descriptor.", flush=True)
|
||||
return reply
|
||||
|
||||
|
||||
def air_m3(info):
|
||||
return (info is not None and info.ids == IPAD
|
||||
and struct.unpack_from("<H", info.descriptor, 12)[0] == REVISION)
|
||||
|
||||
|
||||
def initial_configuration(hub):
|
||||
info = hub.connection()
|
||||
if not air_m3(info) or (info.config, info.count) != (1, 4):
|
||||
raise ValueError("Expected one iPad Air M3 in its initial USB configuration")
|
||||
values = {hub.configuration(index)[5] for index in range(info.count)}
|
||||
if len(values) != info.count or info.config not in values:
|
||||
raise ValueError("The iPad USB configuration descriptors are inconsistent")
|
||||
return info
|
||||
|
||||
|
||||
def superspeed_for_session(hub):
|
||||
raw = hub.query(279, struct.pack("<IIII", hub.port, 16, 4, 0), 16)
|
||||
if len(raw) != 16:
|
||||
raise ValueError("Windows did not report the USB link speed")
|
||||
_, _, _, flags = struct.unpack("<IIII", raw)
|
||||
return bool(flags & 1)
|
||||
|
||||
|
||||
def still_connected(hub, initial, guest):
|
||||
try:
|
||||
current = hub.connection()
|
||||
return (air_m3(current) and current.address == initial.address
|
||||
and guest.current_pid() == guest.pid)
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def export_device(listener, guest, device, done, present):
|
||||
listener.settimeout(0.25)
|
||||
deadline = monotonic() + 25
|
||||
while not done.is_set() and present():
|
||||
if monotonic() >= deadline:
|
||||
raise TimeoutError("QEMU did not connect to the iPad forwarder")
|
||||
try:
|
||||
peer, _ = listener.accept()
|
||||
except TimeoutError:
|
||||
continue
|
||||
with peer:
|
||||
if not peer_is_qemu(peer, guest.pid):
|
||||
continue
|
||||
peer.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
||||
peer.settimeout(0.5)
|
||||
next_check = 0.0
|
||||
|
||||
def stopped():
|
||||
nonlocal next_check
|
||||
if done.is_set():
|
||||
return True
|
||||
now = monotonic()
|
||||
if now >= next_check:
|
||||
next_check = now + 0.25
|
||||
return not present()
|
||||
return False
|
||||
|
||||
usb_redir.serve(peer, device, stopped)
|
||||
return
|
||||
|
||||
|
||||
def remove_guest_device(guest, device_id, chardev):
|
||||
if guest.current_pid() != guest.pid:
|
||||
return
|
||||
with guest.monitor() as qmp:
|
||||
def device_exists():
|
||||
return any(item["name"] == device_id for item in qmp.call("qom-list", path="/machine/peripheral"))
|
||||
|
||||
if device_exists():
|
||||
qmp.call("device_del", id=device_id)
|
||||
deadline = monotonic() + 5
|
||||
while device_exists():
|
||||
if monotonic() >= deadline:
|
||||
raise RuntimeError("QEMU did not remove the iPad device")
|
||||
sleep(0.1)
|
||||
if any(item["label"] == chardev for item in qmp.call("query-chardev")):
|
||||
qmp.call("chardev-remove", id=chardev)
|
||||
|
||||
|
||||
def bridge(guest, device, present):
|
||||
suffix = token_hex(6)
|
||||
device_id, chardev = f"ipad-{suffix}", f"ipad-char-{suffix}"
|
||||
done, errors = Event(), Queue()
|
||||
with socket.socket() as listener:
|
||||
listener.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen(1)
|
||||
port = listener.getsockname()[1]
|
||||
|
||||
def worker():
|
||||
try:
|
||||
export_device(listener, guest, device, done, present)
|
||||
except (OSError, RuntimeError, ValueError) as exc:
|
||||
errors.put(exc)
|
||||
|
||||
exporter = Thread(target=worker)
|
||||
exporter.start()
|
||||
try:
|
||||
with guest.monitor() as qmp:
|
||||
qmp.call("chardev-add", id=chardev, backend={"type": "socket", "data": {
|
||||
"server": False, "addr": {"type": "inet", "data": {"host": "127.0.0.1", "port": str(port)}},
|
||||
}})
|
||||
qmp.call("device_add", driver="usb-redir", id=device_id, chardev=chardev, bus="xhci.0")
|
||||
deadline = monotonic() + 12
|
||||
while monotonic() < deadline and exporter.is_alive():
|
||||
if qmp.call("qom-get", path=f"/machine/peripheral/{device_id}", property="attached") is True:
|
||||
print("iPad attached to the guest USB bus.", flush=True)
|
||||
break
|
||||
sleep(0.15)
|
||||
else:
|
||||
try:
|
||||
raise errors.get_nowait()
|
||||
except Empty:
|
||||
# A guest descriptor read can already have triggered USB re-enumeration.
|
||||
if not device.descriptor_read:
|
||||
raise TimeoutError("The iPad did not attach to the guest USB bus") from None
|
||||
|
||||
deadline = monotonic() + 65
|
||||
while monotonic() < deadline and exporter.is_alive():
|
||||
sleep(0.25)
|
||||
return device.descriptor_read
|
||||
finally:
|
||||
try:
|
||||
remove_guest_device(guest, device_id, chardev)
|
||||
finally:
|
||||
done.set()
|
||||
exporter.join()
|
||||
|
||||
|
||||
def run(guest, directory):
|
||||
with guest.monitor() as qmp:
|
||||
models = qmp.call("device-list-properties", typename="usb-redir")
|
||||
if not any(item["name"] == "chardev" for item in models):
|
||||
raise RuntimeError("The guest QEMU does not support usb-redir")
|
||||
qmp.call("qom-list", path="/machine/peripheral/xhci")
|
||||
backend = backend_from(directory)
|
||||
with driver_session(directory) as driver:
|
||||
selected = driver.expect("selected")
|
||||
with closing(Hub(selected["hub_instance"], int(selected["hub_port"]))) as hub:
|
||||
initial_configuration(hub)
|
||||
driver.stream.write(b"B")
|
||||
driver.expect("replug")
|
||||
print("Unplug the iPad, wait two seconds, then plug it into the same USB port.", flush=True)
|
||||
driver.expect("probe", timeout=105)
|
||||
capture = initial_configuration(hub)
|
||||
driver.stream.write(b"P")
|
||||
driver.expect("switch")
|
||||
with closing(MeasuredIpad(backend, capture, superspeed_for_session(hub))) as device:
|
||||
proof = bridge(guest, device, lambda: still_connected(hub, capture, guest))
|
||||
print("Windows iPad driver restored.", flush=True)
|
||||
return proof
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--vm-dir", required=True, type=Path, help="Directory containing qemu.pid")
|
||||
parser.add_argument("--qmp", type=Path, help="QMP socket path, if outside the VM directory")
|
||||
parser.add_argument("--relay", type=Path, default=Path(__file__).with_name("qmp-relay.exe"))
|
||||
parser.add_argument("--driver-dir", required=True, type=Path, help="Verified libusb-win32 bin/amd64 directory")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
directory = args.vm_dir.resolve(strict=True)
|
||||
# Windows AF_UNIX sockets are reparse points that pathlib cannot resolve.
|
||||
qmp_path = (args.qmp if args.qmp else directory / "qmp.sock").absolute()
|
||||
guest = Guest(directory, qmp_path, args.relay.resolve(strict=True))
|
||||
proof = run(guest, args.driver_dir.resolve(strict=True))
|
||||
except (OSError, ValueError, RuntimeError) as exc:
|
||||
sys.exit(f"iPad USB session: {exc}")
|
||||
if not proof:
|
||||
sys.exit("The guest did not read the iPad device descriptor before the session ended.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,704 @@
|
||||
#requires -Version 7.0
|
||||
# Based on MonchiLin/reims-vgpu@5e69f1ba9d0f0267a670a1fb836b794184ec36bf.
|
||||
# Only the temporary upper-filter transaction runs elevated. Plug changes are user-controlled.
|
||||
[CmdletBinding(DefaultParameterSetName = 'Session')]
|
||||
param(
|
||||
[Parameter(Mandatory, ParameterSetName = 'Session')][string]$DriverDir,
|
||||
[Parameter(Mandatory, ParameterSetName = 'Session')][ValidateRange(1, 2147483647)][int]$OwnerPid,
|
||||
[Parameter(Mandatory, ParameterSetName = 'Session')][ValidatePattern('\A[a-f0-9]{32}\z', Options = 'CultureInvariant')][string]$Token,
|
||||
[Parameter(Mandatory, ParameterSetName = 'Recover')][switch]$Recover
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$script:settings = @('UpperFilters')
|
||||
$script:idPattern = '\AUSB\\VID_05AC&PID_12AB\\[a-zA-Z0-9_&-]{1,160}\z'
|
||||
$script:hardwareId = 'USB\VID_05AC&PID_12AB&REV_1503'
|
||||
$script:driverPattern = '\A\{88bae032-5a81-49f0-bc3d-a4ff138216d6\}\\[0-9]{4}\z'
|
||||
$script:control = 'SYSTEM\CurrentControlSet'
|
||||
$script:journalName = 'SOFTWARE\Reims.WindowsIpadAirM3AttachLab'
|
||||
$script:replugTimeoutSeconds = 90
|
||||
$script:unplugTimeoutSeconds = 90
|
||||
$script:activeTimeoutSeconds = 180
|
||||
# From libusb-win32-bin-1.4.0.2.zip, bin/amd64/libusb0.sys.
|
||||
$script:driverSha256 = 'CDA0070FE4F7C5DE5D3BB06FA6D7E29E6F6740C0F2FA319FB5C1AF235D78D616'
|
||||
|
||||
function Refuse([string]$Message) { throw [System.ApplicationException]::new($Message) }
|
||||
|
||||
function Initialize-Native {
|
||||
if ('ReimsIpad' -as [type]) { return }
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO.Pipes;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Principal;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
|
||||
public static class ReimsIpad {
|
||||
[DllImport("cfgmgr32.dll", ExactSpelling=true, CharSet=CharSet.Unicode)]
|
||||
static extern uint CM_Locate_DevNodeW(out uint node, string id, uint flags);
|
||||
[DllImport("cfgmgr32.dll", ExactSpelling=true)]
|
||||
static extern uint CM_Set_DevNode_Registry_PropertyW(uint node, uint property, byte[] data, uint length, uint flags);
|
||||
[DllImport("cfgmgr32.dll", ExactSpelling=true)]
|
||||
static extern uint CM_Get_DevNode_Status(out uint status, out uint problem, uint node, uint flags);
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct PropertyKey { public Guid Format; public uint Id; }
|
||||
[DllImport("cfgmgr32.dll", ExactSpelling=true)]
|
||||
static extern uint CM_Get_DevNode_PropertyW(uint node, ref PropertyKey key, out uint type,
|
||||
out long value, ref uint size, uint flags);
|
||||
[DllImport("cfgmgr32.dll", ExactSpelling=true, EntryPoint="CM_Get_DevNode_PropertyW")]
|
||||
static extern uint ReadProperty(uint node, ref PropertyKey key, out uint type,
|
||||
[Out] byte[] value, ref uint size, uint flags);
|
||||
[DllImport("advapi32.dll", SetLastError=true)]
|
||||
static extern bool OpenProcessToken(SafeProcessHandle process, uint access, out SafeAccessTokenHandle token);
|
||||
[DllImport("advapi32.dll", SetLastError=true)]
|
||||
static extern bool GetTokenInformation(SafeAccessTokenHandle token, int kind, IntPtr buffer, int size, out int length);
|
||||
[DllImport("kernel32.dll", SetLastError=true)]
|
||||
static extern bool GetNamedPipeClientProcessId(SafePipeHandle pipe, out uint pid);
|
||||
[DllImport("kernel32.dll", SetLastError=true)]
|
||||
static extern bool PeekNamedPipe(SafePipeHandle pipe, IntPtr buffer, uint bufferSize,
|
||||
IntPtr bytesRead, out uint bytesAvailable, IntPtr bytesLeft);
|
||||
|
||||
// CM_LOCATE_DEVNODE_NORMAL only finds present nodes. A phantom keeps its registry values.
|
||||
public static bool Present(string id) {
|
||||
uint rc = CM_Locate_DevNodeW(out uint node, id, 0);
|
||||
if (rc == 0x0d) return false; // CR_NO_SUCH_DEVNODE
|
||||
if (rc != 0) throw new ApplicationException("Windows could not query the iPad device node.");
|
||||
return true;
|
||||
}
|
||||
public static bool Started(string id) {
|
||||
return CM_Locate_DevNodeW(out uint n, id, 0) == 0 &&
|
||||
CM_Get_DevNode_Status(out uint flags, out uint problem, n, 0) == 0 && (flags & 8) != 0 && problem == 0;
|
||||
}
|
||||
public static long Arrival(string id) {
|
||||
var key = new PropertyKey { Format = new Guid("83da6326-97a6-4088-9453-a1923f573b29"), Id = 102 };
|
||||
uint size = 8;
|
||||
if (CM_Locate_DevNodeW(out uint node, id, 0) != 0) return 0;
|
||||
if (CM_Get_DevNode_PropertyW(node, ref key, out uint type, out long value, ref size, 0) != 0 ||
|
||||
type != 0x10 || size != 8) throw new ApplicationException("Windows could not read the iPad arrival time.");
|
||||
return value;
|
||||
}
|
||||
public static uint SetFilters(string id, uint property, byte[] data) {
|
||||
uint rc = CM_Locate_DevNodeW(out uint n, id, 1); // includes disconnected devices
|
||||
return rc == 0 ? CM_Set_DevNode_Registry_PropertyW(n, property, data, (uint)(data?.Length ?? 0), 0) : rc;
|
||||
}
|
||||
static string[] StringListProperty(string id, PropertyKey key, bool allowAbsent) {
|
||||
uint rc = CM_Locate_DevNodeW(out uint node, id, 0);
|
||||
if (rc == 0x0d) return null;
|
||||
if (rc != 0) throw new ApplicationException("Windows could not query the iPad device node.");
|
||||
uint size = 0;
|
||||
rc = ReadProperty(node, ref key, out uint type, null, ref size, 0);
|
||||
if (allowAbsent && rc == 0x25) return Array.Empty<string>(); // CR_NO_SUCH_VALUE
|
||||
if (rc != 0x1a || size == 0 || size > 65536 || (size & 1) != 0)
|
||||
throw new ApplicationException("Could not read the iPad device properties.");
|
||||
var bytes = new byte[size];
|
||||
if (ReadProperty(node, ref key, out type, bytes, ref size, 0) != 0 || type != 0x2012)
|
||||
throw new ApplicationException("Unexpected iPad device property type.");
|
||||
return System.Text.Encoding.Unicode.GetString(bytes, 0, (int)size).Split(new char[]{'\0'}, StringSplitOptions.RemoveEmptyEntries);
|
||||
}
|
||||
public static string[] Filters(string id) {
|
||||
var key = new PropertyKey { Format = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), Id = 19 };
|
||||
return StringListProperty(id, key, true);
|
||||
}
|
||||
public static string[] Stack(string id) {
|
||||
var key = new PropertyKey { Format = new Guid("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), Id = 14 };
|
||||
return StringListProperty(id, key, false);
|
||||
}
|
||||
public static bool HasPipeInput(NamedPipeServerStream pipe) {
|
||||
if (!PeekNamedPipe(pipe.SafePipeHandle, IntPtr.Zero, 0, IntPtr.Zero, out uint available, IntPtr.Zero))
|
||||
throw new Win32Exception();
|
||||
return available != 0;
|
||||
}
|
||||
public static SecurityIdentifier LogonSid(Process owner) {
|
||||
if (!OpenProcessToken(owner.SafeHandle, 8, out var token)) throw new Win32Exception();
|
||||
using (token) {
|
||||
GetTokenInformation(token, 28, IntPtr.Zero, 0, out int size); // TokenLogonSid, TOKEN_GROUPS
|
||||
if (size <= 0) throw new Win32Exception();
|
||||
IntPtr data = Marshal.AllocHGlobal(size);
|
||||
try {
|
||||
if (!GetTokenInformation(token, 28, data, size, out size) || Marshal.ReadInt32(data) != 1)
|
||||
throw new Win32Exception();
|
||||
return new SecurityIdentifier(Marshal.ReadIntPtr(data, IntPtr.Size));
|
||||
} finally { Marshal.FreeHGlobal(data); }
|
||||
}
|
||||
}
|
||||
public static bool IsClient(NamedPipeServerStream pipe, int expected) {
|
||||
return GetNamedPipeClientProcessId(pipe.SafePipeHandle, out uint pid) && pid == expected;
|
||||
}
|
||||
public static NamedPipeServerStream CreateAsOwner(Process owner, Func<NamedPipeServerStream> create) {
|
||||
if (!OpenProcessToken(owner.SafeHandle, 10, out var token)) throw new Win32Exception(); // QUERY | DUPLICATE
|
||||
using (token) return WindowsIdentity.RunImpersonated(token, create);
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
|
||||
function Open-SessionPipe($Owner, [string]$Token) {
|
||||
if ($Owner.SessionId -ne [Diagnostics.Process]::GetCurrentProcess().SessionId -or $Owner.HasExited) {
|
||||
Refuse 'The requesting process left this Windows session.'
|
||||
}
|
||||
$logon = [ReimsIpad]::LogonSid($Owner).Value
|
||||
$security = [IO.Pipes.PipeSecurity]::new()
|
||||
# The client requests GENERIC_READ | GENERIC_WRITE. The logon SID identifies its session,
|
||||
# and both endpoints verify the other's process ID. Create at the caller's integrity level.
|
||||
$security.SetSecurityDescriptorSddlForm("D:P(D;;GA;;;NU)(A;;GA;;;BA)(A;;GA;;;SY)(A;;GRGW;;;$logon)")
|
||||
$options = [IO.Pipes.PipeOptions]::Asynchronous
|
||||
if ('FirstPipeInstance' -in [IO.Pipes.PipeOptions].GetEnumNames()) { $options = $options -bor [IO.Pipes.PipeOptions]::FirstPipeInstance }
|
||||
[ReimsIpad]::CreateAsOwner($Owner, {
|
||||
[IO.Pipes.NamedPipeServerStreamAcl]::Create("reims-ipad-$Token", 'InOut', 1, 'Byte', $options, 256, 4096, $security)
|
||||
})
|
||||
}
|
||||
|
||||
function Send-Status($Pipe, [string]$State, $Fields = @{}) {
|
||||
$Fields.state = $State
|
||||
$line = (ConvertTo-Json -InputObject $Fields -Compress) + [char]10
|
||||
$data = [Text.Encoding]::UTF8.GetBytes($line)
|
||||
$Pipe.Write($data, 0, $data.Length)
|
||||
}
|
||||
|
||||
function Wait-Signal($Pipe, $Owner, [char]$Expected, [string]$DeviceId = '', [long]$Arrival = 0, [int]$ActiveTimeoutSeconds = $script:activeTimeoutSeconds) {
|
||||
$buffer = [byte[]]::new(1)
|
||||
$read = $Pipe.ReadAsync($buffer, 0, 1)
|
||||
$clock = [Diagnostics.Stopwatch]::StartNew()
|
||||
$lastPresent = $clock.Elapsed
|
||||
$switched = $false
|
||||
while (-not $read.Wait(250)) {
|
||||
if ($Owner.HasExited) { return 'R' }
|
||||
if ($DeviceId) {
|
||||
if ($clock.Elapsed.TotalSeconds -ge $ActiveTimeoutSeconds) { return 'R' }
|
||||
# Apple's requested mode switch re-enumerates once. Monitor subsequent arrivals,
|
||||
# including a rapid unplug/replug between two polls.
|
||||
$now = [ReimsIpad]::Arrival($DeviceId)
|
||||
if ($now -ne 0) {
|
||||
if ($arrival -ne $now) {
|
||||
if ($switched -or $clock.Elapsed.TotalSeconds -gt 20) { return 'R' }
|
||||
$switched = $true
|
||||
$arrival = $now
|
||||
}
|
||||
$lastPresent = $clock.Elapsed
|
||||
} elseif (($clock.Elapsed - $lastPresent).TotalSeconds -ge 5) { return 'R' }
|
||||
} elseif ($clock.Elapsed.TotalSeconds -ge 60) { Refuse 'The USB helper timed out during preparation.' }
|
||||
}
|
||||
if ($read.Result -eq 0 -or $Owner.HasExited -or $buffer[0] -eq [byte][char]'R') { return 'R' }
|
||||
if ($buffer[0] -ne [byte]$Expected) { Refuse 'Unexpected USB helper request.' }
|
||||
return [char]$buffer[0]
|
||||
}
|
||||
|
||||
function Read-KeyValue($Key, [string]$Name) {
|
||||
if ($Key.GetValueNames() -notcontains $Name) { return @{ Kind = 'Absent'; Value = $null } }
|
||||
return @{
|
||||
Kind = $Key.GetValueKind($Name).ToString()
|
||||
Value = $Key.GetValue($Name, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
|
||||
}
|
||||
}
|
||||
|
||||
function Test-SameValue($A, $B) {
|
||||
if ($A.Kind -cne $B.Kind) { return $false }
|
||||
if ($A.Kind -ceq 'Absent') { return $true }
|
||||
$left = @($A.Value)
|
||||
$right = @($B.Value)
|
||||
if ($left.Count -ne $right.Count) { return $false }
|
||||
for ($i = 0; $i -lt $left.Count; $i++) {
|
||||
if (-not [string]::Equals([string]$left[$i], [string]$right[$i], [StringComparison]::Ordinal)) { return $false }
|
||||
}
|
||||
return $true
|
||||
}
|
||||
|
||||
function Read-DeviceValue($Journal, $Name) {
|
||||
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("$script:control\Enum\$($Journal.Id)")
|
||||
if (-not $key) { Refuse 'The original device registry key is missing. Reconnect the same iPad and retry.' }
|
||||
try { Read-KeyValue $key $Name } finally { $key.Dispose() }
|
||||
}
|
||||
|
||||
function Write-KeyValue($Key, $Name, $Setting) {
|
||||
if ($Setting.Kind -eq 'Absent') { $Key.DeleteValue($Name, $false); return }
|
||||
if ($Setting.Kind -ne 'MultiString') { Refuse 'Invalid iPad upper filter type.' }
|
||||
$Key.SetValue($Name, [string[]]$Setting.Value, [Microsoft.Win32.RegistryValueKind]::MultiString)
|
||||
}
|
||||
|
||||
function Write-DeviceValue($Journal, $Name, $Setting) {
|
||||
if ($Name -cne 'UpperFilters') { Refuse 'The probe may change only the selected iPad upper filters.' }
|
||||
[byte[]]$data = $null
|
||||
if ($Setting.Kind -ne 'Absent') {
|
||||
$data = [Text.Encoding]::Unicode.GetBytes(($Setting.Value -join [char]0) + [char]0 + [char]0)
|
||||
}
|
||||
$rc = [ReimsIpad]::SetFilters($Journal.Id, 0x12, $data)
|
||||
$alreadyAbsent = $rc -eq 0x25 -and $Setting.Kind -eq 'Absent'
|
||||
if ($rc -ne 0 -and -not $alreadyAbsent -and [ReimsIpad]::Present($Journal.Id)) { Refuse "Windows rejected the iPad upper filter change ($rc)." }
|
||||
# Some stacks retain the raw value after Configuration Manager removes a PnP property.
|
||||
# Read it back. Open for writing only if an explicit raw restore is still necessary.
|
||||
if (-not (Test-SameValue (Read-DeviceValue $Journal $Name) $Setting)) {
|
||||
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("$script:control\Enum\$($Journal.Id)", $true)
|
||||
try { Write-KeyValue $key $Name $Setting; $key.Flush() } finally { if ($key) { $key.Dispose() } }
|
||||
}
|
||||
if (-not (Test-SameValue (Read-DeviceValue $Journal $Name) $Setting)) { Refuse "Windows did not retain the iPad $Name value." }
|
||||
}
|
||||
|
||||
function Get-SettingsPlan($Journal) {
|
||||
$upper = @($Journal.Original.UpperFilters.Value | Where-Object { $null -ne $_ }) + 'libusb0'
|
||||
return [ordered]@{ UpperFilters = @{ Kind = 'MultiString'; Value = $upper } }
|
||||
}
|
||||
|
||||
function Set-ProbeFilter($Journal) {
|
||||
$actual = Read-DeviceValue $Journal 'UpperFilters'
|
||||
if (-not (Test-SameValue $actual $Journal.Original.UpperFilters)) { Refuse 'The iPad upper filters changed outside this session.' }
|
||||
$target = Get-SettingsPlan $Journal
|
||||
Write-DeviceValue $Journal 'UpperFilters' $target.UpperFilters
|
||||
}
|
||||
|
||||
function Assert-DeviceIdentity($Journal) {
|
||||
if ($Journal.Id -notmatch $script:idPattern -or $Journal.Driver -notmatch $script:driverPattern) {
|
||||
Refuse 'Unexpected iPad instance or driver key.'
|
||||
}
|
||||
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("$script:control\Enum\$($Journal.Id)")
|
||||
if (-not $key) { Refuse 'Reconnect the original iPad so its saved driver settings can be restored.' }
|
||||
try {
|
||||
if ($key.GetValue('HardwareID') -notcontains $script:hardwareId -or
|
||||
$key.GetValue('Service') -ne 'usbccgp' -or $key.GetValue('Driver') -ne $Journal.Driver) {
|
||||
Refuse 'The iPad or its Windows driver no longer matches the saved device.'
|
||||
}
|
||||
} finally { $key.Dispose() }
|
||||
}
|
||||
|
||||
function Get-SelectedDevice {
|
||||
$parents = @(Get-PnpDevice -PresentOnly | Where-Object InstanceId -Match '^USB\\VID_05AC&PID_12AB\\')
|
||||
if ($parents.Count -ne 1 -or $parents[0].Status -ne 'OK') { Refuse 'Connect one supported iPad Air M3 to Windows.' }
|
||||
$id = $parents[0].InstanceId
|
||||
if ($id -notmatch $script:idPattern) { Refuse 'Unsupported iPad device identity.' }
|
||||
$props = Get-PnpDeviceProperty -InstanceId $id -KeyName DEVPKEY_Device_Parent, DEVPKEY_Device_Address, DEVPKEY_Device_Driver
|
||||
$hub = ($props | Where-Object KeyName -eq 'DEVPKEY_Device_Parent').Data
|
||||
$port = ($props | Where-Object KeyName -eq 'DEVPKEY_Device_Address').Data
|
||||
$driver = ($props | Where-Object KeyName -eq 'DEVPKEY_Device_Driver').Data
|
||||
if (-not $hub -or $port -lt 1 -or $port -gt 255) { Refuse 'Windows did not identify the iPad USB hub and port.' }
|
||||
$selected = @{ Id = $id; Hub = $hub; Port = [int]$port; Driver = $driver }
|
||||
Assert-DeviceIdentity $selected
|
||||
$shared = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SOFTWARE\usbipd-win\Devices')
|
||||
if ($shared) {
|
||||
try {
|
||||
foreach ($name in $shared.GetSubKeyNames()) {
|
||||
$device = $shared.OpenSubKey($name)
|
||||
if (-not $device) { continue }
|
||||
try {
|
||||
if ($device.GetValue('InstanceId') -eq $id) { Refuse 'Unshare this iPad in usbipd-win before using it here.' }
|
||||
} finally { $device.Dispose() }
|
||||
}
|
||||
} finally { $shared.Dispose() }
|
||||
}
|
||||
return $selected
|
||||
}
|
||||
|
||||
# Check class filters and *all* registered device instances, including unplugged devices.
|
||||
# Do not start if any other device or class could own the temporary libusb0 service.
|
||||
function Assert-NoOtherReference($Key, [int]$Depth, $Journal, [string]$Path = '') {
|
||||
if ($Depth -eq 0) {
|
||||
if ($Path -eq $Journal.Id) { return }
|
||||
foreach ($name in 'Service', 'UpperFilters', 'LowerFilters') {
|
||||
if ($Key.GetValue($name) -contains 'libusb0') { Refuse 'Another Windows device or class uses libusb0.' }
|
||||
}
|
||||
if ($Key.GetValue('Driver') -eq $Journal.Driver) { Refuse 'Another device uses the iPad driver software key.' }
|
||||
return
|
||||
}
|
||||
foreach ($name in $Key.GetSubKeyNames()) {
|
||||
$child = $Key.OpenSubKey($name)
|
||||
if (-not $child) { continue }
|
||||
$next = if ($Path) { "$Path\$name" } else { $name }
|
||||
try { Assert-NoOtherReference $child ($Depth - 1) $Journal $next } finally { $child.Dispose() }
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-ExclusiveUse($Journal) {
|
||||
foreach ($entry in @(@('Enum', 3), @('Control\Class', 1))) {
|
||||
$root = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("$script:control\$($entry[0])")
|
||||
try { Assert-NoOtherReference $root $entry[1] $Journal } finally { $root.Dispose() }
|
||||
}
|
||||
}
|
||||
|
||||
function Invoke-SystemTool([string]$Name, [string[]]$Arguments, [int[]]$Allowed = @(0)) {
|
||||
$info = [Diagnostics.ProcessStartInfo]::new()
|
||||
$info.FileName = [IO.Path]::Combine([Environment]::SystemDirectory, $Name)
|
||||
$info.UseShellExecute = $false
|
||||
$info.CreateNoWindow = $true
|
||||
$info.RedirectStandardOutput = $true
|
||||
$info.RedirectStandardError = $true
|
||||
foreach ($argument in $Arguments) { $info.ArgumentList.Add($argument) }
|
||||
$process = [Diagnostics.Process]::Start($info)
|
||||
try {
|
||||
# Native diagnostics can contain serial numbers. Only the tool and exit code reach the client.
|
||||
$stdout = $process.StandardOutput.ReadToEndAsync()
|
||||
$stderr = $process.StandardError.ReadToEndAsync()
|
||||
if (-not $process.WaitForExit(20000)) { $process.Kill(); Refuse "$Name timed out." }
|
||||
if ($process.ExitCode -notin $Allowed) { Refuse "$Name failed with Windows error $($process.ExitCode)." }
|
||||
} finally { $process.Dispose() }
|
||||
}
|
||||
|
||||
function Get-DeviceArrival($Journal) { [ReimsIpad]::Arrival($Journal.Id) }
|
||||
function Test-DevicePresent($Journal) { [ReimsIpad]::Present($Journal.Id) }
|
||||
function Test-DeviceStarted($Journal) { [ReimsIpad]::Started($Journal.Id) }
|
||||
function Get-EffectiveStack($Journal) { [ReimsIpad]::Stack($Journal.Id) }
|
||||
|
||||
function Assert-SameDevice($Expected, $Current) {
|
||||
if ($Current.Id -ne $Expected.Id -or $Current.Driver -ne $Expected.Driver -or
|
||||
$Current.Hub -ne $Expected.Hub -or $Current.Port -ne $Expected.Port) {
|
||||
Refuse 'Reconnect the same iPad to its original USB port.'
|
||||
}
|
||||
}
|
||||
|
||||
function Wait-ForReplug($Pipe, $Owner, $Journal, [long]$Before, [int]$TimeoutSeconds = $script:replugTimeoutSeconds) {
|
||||
if ($Before -eq 0) { Refuse 'The selected iPad disconnected before filter preparation.' }
|
||||
$clock = [Diagnostics.Stopwatch]::StartNew()
|
||||
$left = $false
|
||||
while ($clock.Elapsed.TotalSeconds -lt $TimeoutSeconds) {
|
||||
if ($Owner.HasExited) { return $false }
|
||||
if ([ReimsIpad]::HasPipeInput($Pipe)) {
|
||||
if ($Pipe.ReadByte() -eq [byte][char]'R') { return $false }
|
||||
Refuse 'Unexpected USB helper request while waiting for the iPad to be replugged.'
|
||||
}
|
||||
$arrival = Get-DeviceArrival $Journal
|
||||
if ($arrival -eq 0) {
|
||||
$left = $true
|
||||
} elseif ($left -and $arrival -ne $Before -and (Test-DeviceStarted $Journal)) {
|
||||
Assert-SameDevice $Journal (Get-SelectedDevice)
|
||||
Assert-FilterStack $Journal (Get-SettingsPlan $Journal)
|
||||
$stack = @(Get-EffectiveStack $Journal)
|
||||
if ($stack -notcontains '\Driver\libusb0' -or $stack -notcontains '\Driver\usbccgp') {
|
||||
Refuse 'Windows did not attach the temporary filter to the replugged iPad.'
|
||||
}
|
||||
return $true
|
||||
}
|
||||
Start-Sleep -Milliseconds 250
|
||||
}
|
||||
Refuse 'Timed out waiting for the iPad to be unplugged and reconnected to its original USB port.'
|
||||
}
|
||||
|
||||
function Wait-ForFilterRelease($Journal, [scriptblock]$NotifyUnplug, [int]$TimeoutSeconds = $script:unplugTimeoutSeconds) {
|
||||
if (-not (Test-DevicePresent $Journal)) { return }
|
||||
try { $stack = @(Get-EffectiveStack $Journal) } catch { $stack = @() }
|
||||
if ($stack -contains '\Driver\usbccgp' -and $stack -notcontains '\Driver\libusb0') { return }
|
||||
|
||||
if ($NotifyUnplug) { & $NotifyUnplug }
|
||||
$clock = [Diagnostics.Stopwatch]::StartNew()
|
||||
while (Test-DevicePresent $Journal) {
|
||||
if ($clock.Elapsed.TotalSeconds -ge $TimeoutSeconds) { Refuse 'Timed out waiting for the iPad to be unplugged. The driver recovery record was kept.' }
|
||||
Start-Sleep -Milliseconds 250
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-FilterStack($Journal, $Expected, [switch]$AllowAbsent) {
|
||||
$actual = [ReimsIpad]::Filters($Journal.Id)
|
||||
if ($null -eq $actual) {
|
||||
if ($AllowAbsent -and -not [ReimsIpad]::Present($Journal.Id)) { return }
|
||||
Refuse 'The selected iPad disconnected during its Windows driver change.'
|
||||
}
|
||||
$wanted = [string[]]@($Expected.UpperFilters.Value | Where-Object { $null -ne $_ })
|
||||
if (-not (Test-SameValue @{ Kind = 'MultiString'; Value = $actual } @{ Kind = 'MultiString'; Value = $wanted })) {
|
||||
Refuse 'The active Windows upper filters differ from the requested iPad filters.'
|
||||
}
|
||||
}
|
||||
|
||||
function Read-FilterService {
|
||||
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("$script:control\Services\libusb0")
|
||||
if (-not $key) { return }
|
||||
try { return @{ ImagePath = $key.GetValue('ImagePath'); Type = $key.GetValue('Type'); Start = $key.GetValue('Start') } }
|
||||
finally { $key.Dispose() }
|
||||
}
|
||||
|
||||
function Get-ImagePath($Journal) {
|
||||
if ($Journal.Cookie -cnotmatch '\A[a-f0-9]{32}\z') { Refuse 'Invalid saved session identifier.' }
|
||||
return "System32\drivers\reims-ipad-m3-attach-$($Journal.Cookie).sys"
|
||||
}
|
||||
|
||||
function Get-ImageFile($Journal) {
|
||||
return [IO.Path]::Combine([Environment]::GetFolderPath('Windows'), (Get-ImagePath $Journal))
|
||||
}
|
||||
|
||||
function Read-DriverBytes([string]$Directory) {
|
||||
if ($Directory -notmatch '\A[A-Za-z]:[\\/]' -or $Directory.Substring(2).Contains(':')) { Refuse 'Use a local driver directory.' }
|
||||
$path = [IO.Path]::GetFullPath([IO.Path]::Combine($Directory, 'libusb0.sys'))
|
||||
$drive = [IO.DriveInfo]::new([IO.Path]::GetPathRoot($path))
|
||||
if ($drive.DriveType -notin 'Fixed', 'Removable') { Refuse 'Use an extracted driver on a local disk.' }
|
||||
for ($part = $path; $part; $part = [IO.Path]::GetDirectoryName($part)) {
|
||||
if (([IO.File]::GetAttributes($part) -band [IO.FileAttributes]::ReparsePoint) -ne 0) {
|
||||
Refuse 'Extract the driver into a directory without symbolic links or junctions.'
|
||||
}
|
||||
}
|
||||
$file = [IO.File]::OpenRead($path)
|
||||
try {
|
||||
if ($file.Length -ne 99224) { Refuse 'Expected the amd64 libusb-win32 1.4.0.2 driver.' }
|
||||
$reader = [IO.BinaryReader]::new($file)
|
||||
try { $bytes = $reader.ReadBytes([int]$file.Length) } finally { $reader.Dispose() }
|
||||
} finally { $file.Dispose() }
|
||||
$sha = [Security.Cryptography.SHA256]::Create()
|
||||
try { $hash = [BitConverter]::ToString($sha.ComputeHash($bytes)).Replace('-', '') } finally { $sha.Dispose() }
|
||||
if ($hash -cne $script:driverSha256) { Refuse 'The supplied driver differs from the released amd64 libusb-win32 1.4.0.2 file.' }
|
||||
return ,$bytes
|
||||
}
|
||||
|
||||
function Install-Filter($Journal, [byte[]]$Bytes) {
|
||||
$image = Get-ImageFile $Journal
|
||||
# CreateNew inside the protected drivers directory. The pinned bytes we verified are the bytes we write.
|
||||
$file = [IO.File]::Open($image, 'CreateNew', 'Write', 'None')
|
||||
try { $file.Write($Bytes, 0, $Bytes.Length); $file.Flush($true) } finally { $file.Dispose() }
|
||||
if ((Get-AuthenticodeSignature -LiteralPath $image).Status -ne 'Valid') { Refuse 'Windows could not validate the libusb-win32 driver signature.' }
|
||||
Invoke-SystemTool 'sc.exe' @('create', 'libusb0', 'type=', 'kernel', 'start=', 'demand', 'binPath=', (Get-ImagePath $Journal))
|
||||
}
|
||||
|
||||
function Remove-FilterService {
|
||||
# 1062 is already stopped, 1072 is marked for deletion, and 1060 is already gone.
|
||||
Invoke-SystemTool 'sc.exe' @('stop', 'libusb0') @(0, 1062, 1072, 1060)
|
||||
Invoke-SystemTool 'sc.exe' @('delete', 'libusb0') @(0, 1072, 1060)
|
||||
$clock = [Diagnostics.Stopwatch]::StartNew()
|
||||
while (Read-FilterService) {
|
||||
if ($clock.Elapsed.TotalSeconds -ge 10) { Refuse 'Windows is still unloading libusb0. Retry recovery after it unloads.' }
|
||||
Start-Sleep -Milliseconds 250
|
||||
}
|
||||
}
|
||||
|
||||
function Remove-SessionImage($Journal) {
|
||||
# Only the random, journal-owned image can be removed, including a partial copy after a crash.
|
||||
[IO.File]::Delete((Get-ImageFile $Journal))
|
||||
}
|
||||
|
||||
function Remove-OwnedDriver($Journal) {
|
||||
$service = Read-FilterService
|
||||
if ($service) {
|
||||
if ($service.ImagePath -ne (Get-ImagePath $Journal) -or $service.Type -ne 1 -or $service.Start -ne 3) {
|
||||
Refuse 'The libusb0 service belongs to another installation. Its configuration was preserved.'
|
||||
}
|
||||
Assert-ExclusiveUse $Journal
|
||||
Remove-FilterService
|
||||
}
|
||||
Remove-SessionImage $Journal
|
||||
}
|
||||
|
||||
function Open-JournalKey([switch]$Create) {
|
||||
$root = [Microsoft.Win32.Registry]::LocalMachine
|
||||
if ($Create) {
|
||||
$acl = [Security.AccessControl.RegistrySecurity]::new()
|
||||
$acl.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;;KA;;;BA)(A;;KA;;;SY)')
|
||||
$key = $root.CreateSubKey($script:journalName, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, $acl)
|
||||
} else { $key = $root.OpenSubKey($script:journalName, $true) }
|
||||
if (-not $key) { return }
|
||||
$acl = $key.GetAccessControl()
|
||||
$trusted = @('S-1-5-32-544', 'S-1-5-18')
|
||||
$rules = @($acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]))
|
||||
if (-not $acl.AreAccessRulesProtected -or $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin $trusted -or
|
||||
@($rules | Where-Object { $_.IdentityReference.Value -notin $trusted }).Count) {
|
||||
$key.Dispose()
|
||||
Refuse 'Windows driver recovery storage has unexpected permissions.'
|
||||
}
|
||||
return $key
|
||||
}
|
||||
|
||||
function Read-Journal {
|
||||
$key = Open-JournalKey
|
||||
if (-not $key) { return }
|
||||
try { $saved = $key.GetValue('Session') } finally { $key.Dispose() }
|
||||
if ($null -ne $saved) {
|
||||
$journal = [Management.Automation.PSSerializer]::Deserialize($saved)
|
||||
if ($journal.Version -ne 1 -or $journal.Stage -notin 'prepared', 'device', 'restored' -or
|
||||
$journal.Id -notmatch $script:idPattern -or $journal.Driver -notmatch $script:driverPattern -or
|
||||
-not $journal.Hub -or $journal.Port -lt 1 -or $journal.Port -gt 255 -or
|
||||
$journal.Cookie -cnotmatch '\A[a-f0-9]{32}\z' -or $journal.Original.Count -ne $script:settings.Count) {
|
||||
Refuse 'The Windows driver recovery record has an unexpected format.'
|
||||
}
|
||||
foreach ($name in $script:settings) {
|
||||
if ($journal.Original[$name].Kind -notin 'Absent', 'MultiString') {
|
||||
Refuse 'The Windows driver recovery record contains an invalid upper filter value.'
|
||||
}
|
||||
}
|
||||
return $journal
|
||||
}
|
||||
}
|
||||
|
||||
function Save-Journal($Journal) {
|
||||
$key = Open-JournalKey -Create
|
||||
try {
|
||||
# Preserve array types, unexpanded strings, and strings that resemble timestamps.
|
||||
$key.SetValue('Session', [Management.Automation.PSSerializer]::Serialize($Journal, 8), 'String')
|
||||
$key.Flush() # A single durable value before any associated operation.
|
||||
} finally { $key.Dispose() }
|
||||
}
|
||||
|
||||
function Clear-Journal {
|
||||
$key = Open-JournalKey
|
||||
if ($key) {
|
||||
try { $key.DeleteValue('Session', $false); $key.Flush() } finally { $key.Dispose() }
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-NoOriginalRecovery($Registry = [Microsoft.Win32.Registry]::LocalMachine) {
|
||||
foreach ($name in 'SOFTWARE\Reims.WindowsIpad', 'SOFTWARE\Reims.WindowsIpadAirM3Lab') {
|
||||
$key = $Registry.OpenSubKey($name)
|
||||
if (-not $key) { continue }
|
||||
try {
|
||||
if ($key.GetValueNames() -contains 'Session') {
|
||||
Refuse 'Another Reims iPad driver session is pending recovery. Restore it with its original helper first.'
|
||||
}
|
||||
} finally { $key.Dispose() }
|
||||
}
|
||||
}
|
||||
|
||||
function New-Journal($Selected) {
|
||||
if ((Read-FilterService) -or [IO.File]::Exists([IO.Path]::Combine([Environment]::SystemDirectory, 'drivers\libusb0.sys'))) {
|
||||
Refuse 'This host already has libusb0 installed. Its existing driver was preserved.'
|
||||
}
|
||||
Assert-ExclusiveUse $Selected
|
||||
$journal = @{
|
||||
Version = 1; Cookie = [guid]::NewGuid().ToString('N'); Stage = 'prepared'
|
||||
Id = $Selected.Id; Driver = $Selected.Driver; Hub = $Selected.Hub; Port = $Selected.Port; Original = [ordered]@{}
|
||||
}
|
||||
if ([IO.File]::Exists((Get-ImageFile $journal))) { Refuse 'The temporary driver image already exists.' }
|
||||
foreach ($name in $script:settings) { $journal.Original[$name] = Read-DeviceValue $journal $name }
|
||||
$lower = Read-DeviceValue $journal 'LowerFilters'
|
||||
if ($journal.Original.UpperFilters.Kind -notin 'Absent', 'MultiString' -or
|
||||
$journal.Original.UpperFilters.Value -contains 'libusb0' -or $lower.Value -contains 'libusb0') {
|
||||
Refuse 'The iPad has an unsupported Windows filter configuration.'
|
||||
}
|
||||
return $journal
|
||||
}
|
||||
|
||||
function Restore-Transaction($Journal, [scriptblock]$NotifyUnplug) {
|
||||
if ($Journal.Stage -eq 'device') {
|
||||
Assert-DeviceIdentity $Journal
|
||||
Assert-ExclusiveUse $Journal
|
||||
$probe = Get-SettingsPlan $Journal
|
||||
foreach ($name in $script:settings) {
|
||||
$actual = Read-DeviceValue $Journal $name
|
||||
if (Test-SameValue $actual $Journal.Original[$name]) { continue }
|
||||
if (-not (Test-SameValue $actual $probe[$name])) {
|
||||
Refuse "The iPad $name value changed outside this session. The recovery record was kept."
|
||||
}
|
||||
Write-DeviceValue $Journal $name $Journal.Original[$name]
|
||||
}
|
||||
foreach ($name in $script:settings) {
|
||||
if (-not (Test-SameValue (Read-DeviceValue $Journal $name) $Journal.Original[$name])) { Refuse "The iPad $name value was not restored." }
|
||||
}
|
||||
Assert-FilterStack $Journal $Journal.Original -AllowAbsent
|
||||
Wait-ForFilterRelease $Journal $NotifyUnplug
|
||||
$Journal.Stage = 'restored'
|
||||
Save-Journal $Journal
|
||||
}
|
||||
Remove-OwnedDriver $Journal
|
||||
Clear-Journal
|
||||
}
|
||||
|
||||
function Get-PublicMessage($ErrorRecord) {
|
||||
$cause = $ErrorRecord.Exception
|
||||
while ($cause) {
|
||||
if ($cause.GetType() -eq [System.ApplicationException]) { return $cause.Message }
|
||||
$cause = $cause.InnerException
|
||||
}
|
||||
# Built-in error messages can carry a serial number, local path or account name.
|
||||
return "Windows could not complete the driver operation ($($ErrorRecord.Exception.GetType().Name))."
|
||||
}
|
||||
|
||||
function Invoke-DriverSession {
|
||||
$identity = [Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())
|
||||
if (-not $identity.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Refuse 'Windows administrator approval is required.' }
|
||||
if ($PSVersionTable.PSEdition -ne 'Core' -or $PSVersionTable.PSVersion.Major -ne 7 -or
|
||||
[Runtime.InteropServices.RuntimeInformation]::OSArchitecture -ne 'X64' -or
|
||||
[Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture -ne 'X64') { Refuse 'Use 64-bit PowerShell 7 on x64 Windows.' }
|
||||
$env:PSModulePath = [IO.Path]::Combine($PSHOME, 'Modules') + ';' + [IO.Path]::Combine([Environment]::SystemDirectory, 'WindowsPowerShell\v1.0\Modules')
|
||||
Set-Location -LiteralPath ([Environment]::SystemDirectory)
|
||||
Initialize-Native
|
||||
$owner = $null
|
||||
$pipe = $null
|
||||
$mutex = $null
|
||||
$locked = $false
|
||||
$trustedPeer = $false
|
||||
$recoveryPending = $false
|
||||
$journal = $null
|
||||
$result = 0
|
||||
$notifyUnplug = {
|
||||
if ($trustedPeer) {
|
||||
try { Send-Status $pipe 'unplug' @{ timeout_seconds = $script:unplugTimeoutSeconds }; return } catch {}
|
||||
}
|
||||
[Console]::Error.WriteLine('Unplug the iPad now to release the temporary driver.')
|
||||
}
|
||||
try {
|
||||
if (-not $Recover) {
|
||||
$owner = [Diagnostics.Process]::GetProcessById($OwnerPid)
|
||||
$pipe = Open-SessionPipe $owner $Token
|
||||
$connected = $pipe.WaitForConnectionAsync()
|
||||
$clock = [Diagnostics.Stopwatch]::StartNew()
|
||||
while (-not $connected.Wait(250)) {
|
||||
if ($owner.HasExited -or $clock.Elapsed.TotalSeconds -ge 45) { Refuse 'The requesting USB helper did not connect.' }
|
||||
}
|
||||
$trustedPeer = [ReimsIpad]::IsClient($pipe, $OwnerPid) -and -not $owner.HasExited
|
||||
if (-not $trustedPeer) { Refuse 'The connected process is not the requesting USB helper.' }
|
||||
}
|
||||
$security = [Security.AccessControl.MutexSecurity]::new()
|
||||
$security.SetSecurityDescriptorSddlForm('D:P(A;;GA;;;BA)(A;;GA;;;SY)')
|
||||
$created = $false
|
||||
$mutex = [Threading.MutexAcl]::Create($false, 'Global\Reims.WindowsIpad.DriverSession', [ref]$created, $security)
|
||||
try { $locked = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $locked = $true }
|
||||
if (-not $locked) { Refuse 'Another Windows iPad driver session is active.' }
|
||||
Assert-NoOriginalRecovery
|
||||
$recoveryPending = $true
|
||||
$stale = Read-Journal
|
||||
if ($stale) {
|
||||
if (-not $Recover) { Refuse 'An iPad Air M3 driver recovery is pending. Unplug the iPad and run this helper with -Recover.' }
|
||||
Restore-Transaction $stale $notifyUnplug
|
||||
}
|
||||
$recoveryPending = $false
|
||||
if (-not $Recover) {
|
||||
$bytes = Read-DriverBytes $DriverDir
|
||||
$device = Get-SelectedDevice
|
||||
Send-Status $pipe 'selected' @{ instance_id = $device.Id; hub_instance = $device.Hub; hub_port = $device.Port }
|
||||
if ((Wait-Signal $pipe $owner 'B') -eq 'B') {
|
||||
Assert-SameDevice $device (Get-SelectedDevice)
|
||||
$before = Get-DeviceArrival $device
|
||||
if ($before -eq 0) { Refuse 'The selected iPad disconnected before filter preparation.' }
|
||||
$baselineStack = @(Get-EffectiveStack $device)
|
||||
if ($baselineStack -notcontains '\Driver\usbccgp' -or $baselineStack -contains '\Driver\libusb0') {
|
||||
Refuse 'The iPad does not have its expected Windows device stack.'
|
||||
}
|
||||
$prepared = New-Journal $device
|
||||
Save-Journal $prepared
|
||||
$journal = $prepared
|
||||
Install-Filter $journal $bytes
|
||||
$journal.Stage = 'device'
|
||||
Save-Journal $journal
|
||||
Set-ProbeFilter $journal
|
||||
Send-Status $pipe 'replug' @{ timeout_seconds = $script:replugTimeoutSeconds }
|
||||
if (Wait-ForReplug $pipe $owner $journal $before) {
|
||||
Send-Status $pipe 'probe'
|
||||
if ((Wait-Signal $pipe $owner 'P') -eq 'P') {
|
||||
Assert-SameDevice $journal (Get-SelectedDevice)
|
||||
$arrival = Get-DeviceArrival $journal
|
||||
Send-Status $pipe 'switch' @{ timeout_seconds = $script:activeTimeoutSeconds }
|
||||
$null = Wait-Signal $pipe $owner 'R' $journal.Id $arrival
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
$result = 1
|
||||
$message = Get-PublicMessage $_
|
||||
if ($trustedPeer) { try { Send-Status $pipe 'error' @{ message = $message } } catch {} }
|
||||
else { [Console]::Error.WriteLine($message) }
|
||||
} finally {
|
||||
try {
|
||||
if ($journal) { Restore-Transaction $journal $notifyUnplug }
|
||||
if ($trustedPeer -and -not $recoveryPending) { try { Send-Status $pipe 'restored' } catch {} }
|
||||
} catch {
|
||||
$result = 1
|
||||
$message = 'iPad recovery is pending. Reconnect the same iPad and run -Recover. ' + (Get-PublicMessage $_)
|
||||
if ($trustedPeer) { try { Send-Status $pipe 'error' @{ message = $message } } catch {} }
|
||||
else { [Console]::Error.WriteLine($message) }
|
||||
} finally {
|
||||
if ($locked) { $mutex.ReleaseMutex() }
|
||||
if ($mutex) { $mutex.Dispose() }
|
||||
if ($pipe) { $pipe.Dispose() }
|
||||
if ($owner) { $owner.Dispose() }
|
||||
}
|
||||
}
|
||||
return $result
|
||||
}
|
||||
|
||||
if ($MyInvocation.InvocationName -ne '.') {
|
||||
try { exit (Invoke-DriverSession) }
|
||||
catch { [Console]::Error.WriteLine((Get-PublicMessage $_)); exit 1 }
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
"""Request normal Windows elevation for the driver worker and supervise its pipe."""
|
||||
|
||||
from contextlib import contextmanager
|
||||
import ctypes as ct
|
||||
from ctypes import wintypes as wt
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import shutil
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
|
||||
def peer_is_qemu(peer, expected_pid):
|
||||
"""Match the reverse (client) half of the accepted loopback connection."""
|
||||
table = ct.WinDLL("iphlpapi").GetExtendedTcpTable
|
||||
table.argtypes = (ct.c_void_p, ct.POINTER(wt.DWORD), wt.BOOL, wt.ULONG, wt.DWORD, wt.ULONG)
|
||||
size = wt.DWORD()
|
||||
data = None
|
||||
for _ in range(4):
|
||||
status = table(data, ct.byref(size), False, socket.AF_INET, 4, 0)
|
||||
if status == 0 and data is not None:
|
||||
break
|
||||
if status != 122:
|
||||
raise OSError(f"could not inspect the QEMU TCP connection ({status})")
|
||||
data = ct.create_string_buffer(size.value)
|
||||
else:
|
||||
raise OSError("Windows TCP table kept changing")
|
||||
client_ip, client_port = peer.getpeername()
|
||||
server_ip, server_port = peer.getsockname()
|
||||
rows = struct.unpack_from("<I", data)[0]
|
||||
for state, local, sport, remote, dport, owner in struct.iter_unpack("<I4sI4sII", data.raw[4:4 + rows * 24]):
|
||||
if (owner == expected_pid and state == 5 and local == socket.inet_aton(client_ip)
|
||||
and remote == socket.inet_aton(server_ip) and socket.ntohs(sport & 0xffff) == client_port
|
||||
and socket.ntohs(dport & 0xffff) == server_port):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class ShellExecuteInfo(ct.Structure):
|
||||
_fields_ = [
|
||||
("cbSize", wt.DWORD), ("fMask", wt.ULONG), ("hwnd", wt.HWND), ("lpVerb", wt.LPCWSTR),
|
||||
("lpFile", wt.LPCWSTR), ("lpParameters", wt.LPCWSTR), ("lpDirectory", wt.LPCWSTR),
|
||||
("nShow", ct.c_int), ("hInstApp", wt.HINSTANCE), ("lpIDList", ct.c_void_p),
|
||||
("lpClass", wt.LPCWSTR), ("hkeyClass", wt.HKEY), ("dwHotKey", wt.DWORD),
|
||||
("hIcon", wt.HANDLE), ("hProcess", wt.HANDLE),
|
||||
]
|
||||
|
||||
|
||||
class Driver:
|
||||
def __init__(self, directory):
|
||||
self.api = ct.WinDLL("kernel32", use_last_error=True)
|
||||
self.api.GetProcessId.argtypes = (wt.HANDLE,)
|
||||
self.api.GetProcessId.restype = wt.DWORD
|
||||
self.api.GetNamedPipeServerProcessId.argtypes = (wt.HANDLE, ct.POINTER(wt.ULONG))
|
||||
self.api.PeekNamedPipe.argtypes = (wt.HANDLE, ct.c_void_p, wt.DWORD, ct.c_void_p,
|
||||
ct.POINTER(wt.DWORD), ct.c_void_p)
|
||||
self.api.GetExitCodeProcess.argtypes = (wt.HANDLE, ct.POINTER(wt.DWORD))
|
||||
self.api.WaitForSingleObject.argtypes = (wt.HANDLE, wt.DWORD)
|
||||
self.api.WaitForSingleObject.restype = wt.DWORD
|
||||
self.api.CloseHandle.argtypes = (wt.HANDLE,)
|
||||
self.api.CreateFileW.argtypes = (wt.LPCWSTR, wt.DWORD, wt.DWORD, ct.c_void_p, wt.DWORD,
|
||||
wt.DWORD, wt.HANDLE)
|
||||
self.api.CreateFileW.restype = wt.HANDLE
|
||||
shell = ct.WinDLL("shell32", use_last_error=True)
|
||||
shell.ShellExecuteExW.argtypes = (ct.POINTER(ShellExecuteInfo),)
|
||||
if shell.IsUserAnAdmin():
|
||||
raise PermissionError("start reims-ctl from an unelevated terminal")
|
||||
token = secrets.token_hex(16)
|
||||
self.name = r"\\.\pipe\reims-ipad-" + token
|
||||
self.stream = None
|
||||
self.buffer = bytearray()
|
||||
pwsh = shutil.which("pwsh.exe")
|
||||
if not pwsh:
|
||||
raise FileNotFoundError("PowerShell 7 (pwsh.exe) is required")
|
||||
args = ["-NoProfile", "-NonInteractive", "-File", str(Path(__file__).with_name("driver-session.ps1")),
|
||||
"-DriverDir", str(directory), "-OwnerPid", str(os.getpid()), "-Token", token]
|
||||
# The OS displays the UAC consent dialog. Only the driver supervisor is elevated.
|
||||
sei = ShellExecuteInfo(cbSize=ct.sizeof(ShellExecuteInfo), fMask=0x40 | 0x100,
|
||||
lpVerb="runas", lpFile=pwsh, lpParameters=subprocess.list2cmdline(args), nShow=0)
|
||||
if not shell.ShellExecuteExW(ct.byref(sei)):
|
||||
raise ct.WinError(ct.get_last_error())
|
||||
self.process = sei.hProcess
|
||||
|
||||
def exited(self):
|
||||
return self.api.WaitForSingleObject(self.process, 0) == 0
|
||||
|
||||
def connect(self):
|
||||
import msvcrt
|
||||
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
# SECURITY_IDENTIFICATION prevents another pipe server from impersonating this client.
|
||||
handle = self.api.CreateFileW(self.name, 0xc0000000, 0, None, 3, 0x110000, None)
|
||||
if handle != ct.c_void_p(-1).value:
|
||||
pid = wt.ULONG()
|
||||
if (not self.api.GetNamedPipeServerProcessId(handle, ct.byref(pid))
|
||||
or pid.value != self.api.GetProcessId(self.process)):
|
||||
self.api.CloseHandle(handle)
|
||||
raise OSError("the driver pipe belongs to another process")
|
||||
self.stream = os.fdopen(msvcrt.open_osfhandle(handle, os.O_RDWR | os.O_BINARY), "r+b", buffering=0)
|
||||
self.handle = handle
|
||||
return
|
||||
if ct.get_last_error() not in (2, 231) or self.exited():
|
||||
raise OSError("the driver worker exited before connecting")
|
||||
time.sleep(0.1)
|
||||
raise TimeoutError("timed out waiting for the driver worker")
|
||||
|
||||
def message(self, timeout=90):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
end = self.buffer.find(b"\n")
|
||||
if end >= 0:
|
||||
line = self.buffer[:end]
|
||||
del self.buffer[:end + 1]
|
||||
msg = json.loads(line.decode("utf-8-sig"))
|
||||
if not isinstance(msg, dict) or not isinstance(msg.get("state"), str):
|
||||
raise ValueError("unexpected driver response")
|
||||
return msg
|
||||
if len(self.buffer) > 8192:
|
||||
raise ValueError("driver response is too long")
|
||||
available = wt.DWORD()
|
||||
if not self.api.PeekNamedPipe(self.handle, None, 0, None, ct.byref(available), None):
|
||||
raise OSError("the driver worker closed its connection")
|
||||
if available.value:
|
||||
self.buffer.extend(self.stream.read(min(available.value, 8192)))
|
||||
elif self.exited():
|
||||
raise OSError("the driver worker exited before reporting its state")
|
||||
else:
|
||||
time.sleep(0.05)
|
||||
raise TimeoutError("the driver worker did not respond")
|
||||
|
||||
def expect(self, state, timeout=90):
|
||||
message = self.message(timeout)
|
||||
if message["state"] != state:
|
||||
raise OSError(message.get("message") or "unexpected driver state: " + message["state"])
|
||||
return message
|
||||
|
||||
def release(self):
|
||||
# If a busy stage has just finished, drain that status as well.
|
||||
error = None
|
||||
if self.stream:
|
||||
try:
|
||||
try:
|
||||
self.stream.write(b"R")
|
||||
except BrokenPipeError:
|
||||
pass # An unplug can complete restoration before we request it.
|
||||
while True:
|
||||
msg = self.message(105)
|
||||
if msg["state"] == "unplug":
|
||||
print("Unplug the iPad and leave it disconnected until Windows restoration finishes.", flush=True)
|
||||
if msg["state"] == "restored":
|
||||
break
|
||||
if msg["state"] == "error":
|
||||
error = msg.get("message", "driver worker failed")
|
||||
except OSError as exc:
|
||||
error = error or str(exc)
|
||||
finally:
|
||||
self.stream.close()
|
||||
if self.api.WaitForSingleObject(self.process, 110000) != 0:
|
||||
raise TimeoutError("the elevated driver worker is still restoring the iPad")
|
||||
status = wt.DWORD()
|
||||
if not self.api.GetExitCodeProcess(self.process, ct.byref(status)):
|
||||
raise ct.WinError(ct.get_last_error())
|
||||
if error or status.value:
|
||||
raise OSError(error or f"driver worker failed with exit code {status.value}")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def driver_session(directory):
|
||||
driver = Driver(directory)
|
||||
try:
|
||||
driver.connect()
|
||||
yield driver
|
||||
finally:
|
||||
try:
|
||||
driver.release()
|
||||
finally:
|
||||
driver.api.CloseHandle(driver.process)
|
||||
@@ -0,0 +1,27 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 2 {
|
||||
os.Exit(2)
|
||||
}
|
||||
conn, err := net.DialTimeout("unix", os.Args[1], 6*time.Second)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer conn.Close()
|
||||
_ = conn.SetDeadline(time.Now().Add(25 * time.Second))
|
||||
go func() {
|
||||
_, _ = io.Copy(conn, os.Stdin)
|
||||
_ = conn.Close()
|
||||
}()
|
||||
_, _ = io.Copy(os.Stdout, conn)
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
#requires -Version 7.0
|
||||
# Run in an unelevated PowerShell 7. All device and service operations use in-memory fixtures.
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$principal = [Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())
|
||||
if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Run these fixtures unelevated.' }
|
||||
$source = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '../driver-session.ps1')).Path
|
||||
$tokens = $null
|
||||
$errors = $null
|
||||
$null = [Management.Automation.Language.Parser]::ParseFile($source, [ref]$tokens, [ref]$errors)
|
||||
if ($errors.Count) { throw $errors[0].Message }
|
||||
. $source -Recover
|
||||
|
||||
function Assert($Condition, [string]$Message) { if (-not $Condition) { throw $Message } }
|
||||
function Expect-Failure([scriptblock]$Action, [string]$Pattern) {
|
||||
$message = $null
|
||||
try { & $Action } catch { $message = $_.Exception.Message }
|
||||
Assert ($message -like $Pattern) "Expected failure '$Pattern', got '$message'"
|
||||
}
|
||||
|
||||
$originals = [ordered]@{
|
||||
UpperFilters = @{ Kind = 'MultiString'; Value = @('existing-upper') }
|
||||
LowerFilters = @{ Kind = 'MultiString'; Value = @('first', 'AppleLowerFilter', 'last') }
|
||||
OriginalConfigurationValue = @{ Kind = 'ExpandString'; Value = '%example%' }
|
||||
AltConfigurationValue = @{ Kind = 'Absent'; Value = $null }
|
||||
EnumeratorClass = @{ Kind = 'Binary'; Value = @(12, 0, 255) }
|
||||
}
|
||||
$journal = @{
|
||||
Version = 1; Cookie = ('a' * 32); Stage = 'device'
|
||||
Id = 'USB\VID_05AC&PID_12AB\FIXTURE'; Driver = '{88bae032-5a81-49f0-bc3d-a4ff138216d6}\0001'
|
||||
Hub = 'USB\ROOT_HUB30\FIXTURE'; Port = 4
|
||||
Original = [ordered]@{ UpperFilters = $originals.UpperFilters }
|
||||
}
|
||||
function Copy-Object($Value) { [Management.Automation.PSSerializer]::Deserialize([Management.Automation.PSSerializer]::Serialize($Value, 8)) }
|
||||
|
||||
class FixtureRegistryKey {
|
||||
[hashtable]$Values = @{}
|
||||
[hashtable]$Kinds = @{}
|
||||
[int]$Flushes = 0
|
||||
|
||||
[string[]] GetValueNames() { return @($this.Values.Keys) }
|
||||
[object] GetValueKind([string]$Name) { return $this.Kinds[$Name] }
|
||||
[object] GetValue([string]$Name) { return $this.Values[$Name] }
|
||||
[object] GetValue([string]$Name, [object]$Default, [object]$Options) {
|
||||
if (-not $this.Values.ContainsKey($Name)) { return $Default }
|
||||
return $this.Values[$Name]
|
||||
}
|
||||
[void] SetValue([string]$Name, [object]$Value, [object]$Kind) {
|
||||
$this.Values[$Name] = $Value
|
||||
$this.Kinds[$Name] = $Kind
|
||||
}
|
||||
[void] DeleteValue([string]$Name, [bool]$ThrowIfMissing) {
|
||||
$this.Values.Remove($Name)
|
||||
$this.Kinds.Remove($Name)
|
||||
}
|
||||
[void] Flush() { $this.Flushes++ }
|
||||
[void] Dispose() {}
|
||||
}
|
||||
|
||||
# Round-trip the journal with an in-memory registry double.
|
||||
function Test-RegistryRoundTrip {
|
||||
$journalKey = [FixtureRegistryKey]::new()
|
||||
function Open-JournalKey([switch]$Create) { return $journalKey }
|
||||
foreach ($sample in @($originals.UpperFilters, @{ Kind = 'Absent'; Value = $null })) {
|
||||
Write-KeyValue $journalKey 'Sample' $sample
|
||||
Assert (Test-SameValue $sample (Read-KeyValue $journalKey 'Sample')) "registry round-trip $($sample.Kind)"
|
||||
$snapshot = Copy-Object $journal
|
||||
$snapshot.Original.UpperFilters = $sample
|
||||
Save-Journal $snapshot
|
||||
Assert (Test-SameValue (Read-Journal).Original.UpperFilters $sample) "journal round-trip $($sample.Kind)"
|
||||
}
|
||||
Clear-Journal
|
||||
Assert ($null -eq (Read-Journal) -and $journalKey.Flushes -eq 3) 'journal clearance or missing flush'
|
||||
}
|
||||
Test-RegistryRoundTrip
|
||||
|
||||
$legacyKey = [FixtureRegistryKey]::new()
|
||||
$probeKey = [FixtureRegistryKey]::new()
|
||||
$registry = [pscustomobject]@{ LegacyKey = $legacyKey; ProbeKey = $probeKey }
|
||||
$registry | Add-Member -MemberType ScriptMethod -Name OpenSubKey -Value {
|
||||
param($Path)
|
||||
switch -CaseSensitive ($Path) {
|
||||
'SOFTWARE\Reims.WindowsIpad' { return $this.LegacyKey }
|
||||
'SOFTWARE\Reims.WindowsIpadAirM3Lab' { return $this.ProbeKey }
|
||||
default { throw 'Unexpected registry path.' }
|
||||
}
|
||||
}
|
||||
Assert-NoOriginalRecovery $registry
|
||||
foreach ($key in @($legacyKey, $probeKey)) {
|
||||
$key.SetValue('Session', 'pending', 'String')
|
||||
Expect-Failure { Assert-NoOriginalRecovery $registry } '*Another Reims iPad driver session is pending recovery*'
|
||||
Assert ($key.Values.Session -ceq 'pending') 'foreign journal was touched'
|
||||
$key.DeleteValue('Session', $false)
|
||||
}
|
||||
Assert ($script:hardwareId -ceq 'USB\VID_05AC&PID_12AB&REV_1503') 'model guard changed'
|
||||
Assert ($script:journalName -ceq 'SOFTWARE\Reims.WindowsIpadAirM3AttachLab') 'M3 attach journal must stay separate'
|
||||
Expect-Failure { Write-DeviceValue $journal 'LowerFilters' $originals.LowerFilters } '*only the selected iPad upper filters*'
|
||||
|
||||
# Exercise the real logon ACL, PID check and protocol without launching an elevated process.
|
||||
function Test-PrivatePipe {
|
||||
Initialize-Native
|
||||
$owner = [Diagnostics.Process]::GetCurrentProcess()
|
||||
$token = [guid]::NewGuid().ToString('N')
|
||||
$server = Open-SessionPipe $owner $token
|
||||
$client = [IO.Pipes.NamedPipeClientStream]::new('.', "reims-ipad-$token", 'InOut', 'Asynchronous')
|
||||
try {
|
||||
$pending = $server.WaitForConnectionAsync()
|
||||
$client.Connect(2000)
|
||||
Assert ($pending.Wait(2000) -and [ReimsIpad]::IsClient($server, $PID) -and -not [ReimsIpad]::IsClient($server, 0)) 'pipe client PID'
|
||||
$reader = [IO.StreamReader]::new($client)
|
||||
Send-Status $server 'selected' @{ hub_port = 4 }
|
||||
$message = ConvertFrom-Json $reader.ReadLine()
|
||||
Assert ($message.state -ceq 'selected' -and $message.hub_port -eq 4) 'pipe status'
|
||||
$client.WriteByte([byte][char]'B')
|
||||
Assert ((Wait-Signal $server $owner 'B') -ceq 'B') 'begin signal'
|
||||
$client.WriteByte([byte][char]'X')
|
||||
Expect-Failure { Wait-Signal $server $owner 'P' } '*Unexpected USB helper request*'
|
||||
$client.WriteByte([byte][char]'R')
|
||||
Assert ((Wait-Signal $server $owner 'P') -ceq 'R') 'early release'
|
||||
Assert ((Wait-Signal $server @{ HasExited = $true } 'P') -ceq 'R') 'parent exit while waiting'
|
||||
} finally { $client.Dispose(); $server.Dispose(); $owner.Dispose() }
|
||||
}
|
||||
Test-PrivatePipe
|
||||
|
||||
function Test-ManualReplug {
|
||||
$owner = [Diagnostics.Process]::GetCurrentProcess()
|
||||
$token = [guid]::NewGuid().ToString('N')
|
||||
$server = Open-SessionPipe $owner $token
|
||||
$client = [IO.Pipes.NamedPipeClientStream]::new('.', "reims-ipad-$token", 'InOut', 'Asynchronous')
|
||||
$arrivals = [Collections.Generic.Queue[long]]::new()
|
||||
$current = Copy-Object $journal
|
||||
$stack = [Collections.Generic.List[string]]::new()
|
||||
$stack.Add('\Driver\usbccgp')
|
||||
$stack.Add('\Driver\libusb0')
|
||||
function Get-DeviceArrival($Journal) { $arrivals.Dequeue() }
|
||||
function Test-DeviceStarted($Journal) { return $true }
|
||||
function Get-SelectedDevice { return $current }
|
||||
function Get-EffectiveStack($Journal) { return $stack }
|
||||
function Assert-FilterStack($Journal, $Expected) {}
|
||||
try {
|
||||
$pending = $server.WaitForConnectionAsync()
|
||||
$client.Connect(2000)
|
||||
Assert ($pending.Wait(2000)) 'replug fixture pipe connection'
|
||||
$client.WriteByte([byte][char]'R')
|
||||
Assert (-not (Wait-ForReplug $server $owner $journal 100)) 'replug ignored cancellation'
|
||||
Expect-Failure { Wait-ForReplug $server $owner $journal 100 -TimeoutSeconds 0 } '*Timed out waiting for the iPad*'
|
||||
foreach ($arrival in @(100, 0, 101)) { $arrivals.Enqueue($arrival) }
|
||||
Assert (Wait-ForReplug $server $owner $journal 100) 'valid replug did not activate'
|
||||
$client.WriteByte([byte][char]'P')
|
||||
Assert ((Wait-Signal $server $owner 'P') -ceq 'P') 'replug reader consumed next-phase signal'
|
||||
$current.Port = 9
|
||||
foreach ($arrival in @(0, 102)) { $arrivals.Enqueue($arrival) }
|
||||
Expect-Failure { Wait-ForReplug $server $owner $journal 101 } '*original USB port*'
|
||||
$current.Port = $journal.Port
|
||||
$stack.RemoveAt(1)
|
||||
foreach ($arrival in @(0, 103)) { $arrivals.Enqueue($arrival) }
|
||||
Expect-Failure { Wait-ForReplug $server $owner $journal 102 } '*did not attach the temporary filter*'
|
||||
} finally { $client.Dispose(); $server.Dispose(); $owner.Dispose() }
|
||||
}
|
||||
Test-ManualReplug
|
||||
|
||||
# An unanswered active wait returns even while a device might remain present.
|
||||
$owner = [Diagnostics.Process]::GetCurrentProcess()
|
||||
$token = [guid]::NewGuid().ToString('N')
|
||||
$server = Open-SessionPipe $owner $token
|
||||
$client = [IO.Pipes.NamedPipeClientStream]::new('.', "reims-ipad-$token", 'InOut', 'Asynchronous')
|
||||
try {
|
||||
$pending = $server.WaitForConnectionAsync()
|
||||
$client.Connect(2000)
|
||||
Assert ($pending.Wait(2000)) 'timeout fixture pipe connection'
|
||||
Assert ((Wait-Signal $server $owner 'R' -DeviceId 'fixture-only' -ActiveTimeoutSeconds 0) -ceq 'R') 'active timeout'
|
||||
} finally { $client.Dispose(); $server.Dispose(); $owner.Dispose() }
|
||||
|
||||
$directory = [IO.Directory]::CreateDirectory([IO.Path]::Combine([IO.Path]::GetTempPath(), 'reims-ipad-test-' + [guid]::NewGuid().ToString('N')))
|
||||
$file = [IO.Path]::Combine($directory.FullName, 'libusb0.sys')
|
||||
try {
|
||||
[IO.File]::WriteAllBytes($file, [byte[]]::new(99224))
|
||||
Expect-Failure { Read-DriverBytes $directory.FullName } '*differs from the released*'
|
||||
} finally { [IO.File]::Delete($file); $directory.Delete() }
|
||||
function Reset-Fixture {
|
||||
$script:values = Copy-Object $originals
|
||||
$script:journal = Copy-Object $journal
|
||||
$script:journal.Stage = 'device'
|
||||
$script:present = $true
|
||||
$script:stack = @('\Driver\usbccgp', '\Driver\AppleLowerFilter')
|
||||
$script:unplugs = 0
|
||||
$script:hardwareWrites = 0
|
||||
$script:removed = $false
|
||||
$script:saved = $null
|
||||
}
|
||||
function Assert-DeviceIdentity($Journal) {}
|
||||
function Assert-ExclusiveUse($Journal) {}
|
||||
function Read-DeviceValue($Journal, $Name) { $script:values[$Name] }
|
||||
function Write-DeviceValue($Journal, $Name, $Value) {
|
||||
$script:hardwareWrites++
|
||||
$script:values[$Name] = Copy-Object $Value
|
||||
}
|
||||
function Test-DevicePresent($Journal) { return $script:present }
|
||||
function Get-EffectiveStack($Journal) { return $script:stack }
|
||||
function Assert-FilterStack($Journal, $Expected, [switch]$AllowAbsent) {}
|
||||
function Save-Journal($Journal) { $script:saved = Copy-Object $Journal }
|
||||
function Clear-Journal { $script:saved = $null }
|
||||
|
||||
# Exercise real ownership checks with fake SCM/registry and filesystem endpoints.
|
||||
$realRemove = ${function:Remove-OwnedDriver}
|
||||
function Remove-OwnedDriver($Journal) { $script:removed = $true }
|
||||
|
||||
Reset-Fixture
|
||||
Set-ProbeFilter $journal
|
||||
Assert (($values.UpperFilters.Value -join ',') -ceq 'existing-upper,libusb0') 'upper filter was not appended'
|
||||
foreach ($name in $originals.Keys | Where-Object { $_ -ne 'UpperFilters' }) {
|
||||
Assert (Test-SameValue $values[$name] $originals[$name]) "changed untouched value $name"
|
||||
}
|
||||
Assert ($hardwareWrites -eq 1) 'probe wrote more than the upper filter'
|
||||
$script:present = $false
|
||||
Restore-Transaction $journal
|
||||
foreach ($name in $originals.Keys) { Assert (Test-SameValue $values[$name] $originals[$name]) "restore $name" }
|
||||
Assert ($unplugs -eq 0 -and $removed -and $null -eq $saved) 'unplugged rollback did not finish'
|
||||
|
||||
# The journal precedes file/service creation and every device mutation. Replay from each cut point.
|
||||
foreach ($count in 0..1) {
|
||||
Reset-Fixture
|
||||
$plan = Get-SettingsPlan $journal
|
||||
foreach ($name in @($plan.Keys | Select-Object -First $count)) { $values[$name] = $plan[$name] }
|
||||
Restore-Transaction (Copy-Object $journal)
|
||||
foreach ($name in $originals.Keys) { Assert (Test-SameValue $values[$name] $originals[$name]) "crash after $count/$name" }
|
||||
Assert ($removed -and $null -eq $saved) "crash after $count kept resources"
|
||||
}
|
||||
Reset-Fixture
|
||||
$journal.Stage = 'prepared'
|
||||
Restore-Transaction $journal
|
||||
Assert ($unplugs -eq 0 -and $hardwareWrites -eq 0 -and $removed) 'preparation touched the device'
|
||||
Reset-Fixture
|
||||
Set-ProbeFilter $journal
|
||||
$values.UpperFilters = @{ Kind = 'MultiString'; Value = @('external-filter') }
|
||||
Expect-Failure { Restore-Transaction $journal } '*changed outside*'
|
||||
Assert ($values.UpperFilters.Value[0] -eq 'external-filter' -and -not $removed) 'changed a foreign filter'
|
||||
|
||||
Reset-Fixture
|
||||
Set-ProbeFilter $journal
|
||||
$values.LowerFilters = @{ Kind = 'MultiString'; Value = @('external-lower-filter') }
|
||||
$script:stack += '\Driver\libusb0'
|
||||
Save-Journal $journal
|
||||
$defaultTimeout = $script:unplugTimeoutSeconds
|
||||
try {
|
||||
$script:unplugTimeoutSeconds = 0
|
||||
Expect-Failure { Restore-Transaction $journal { $script:unplugs++ } } '*Timed out waiting for the iPad to be unplugged*'
|
||||
} finally { $script:unplugTimeoutSeconds = $defaultTimeout }
|
||||
Assert ((Test-SameValue $values.UpperFilters $originals.UpperFilters) -and $unplugs -eq 1) 'unplug must be requested after restoring the registry'
|
||||
Assert (-not $removed -and $saved.Stage -ceq 'device') 'timed out cleanup discarded its recovery state'
|
||||
Restore-Transaction $journal {
|
||||
Assert (Test-SameValue $values.UpperFilters $originals.UpperFilters) 'registry not restored before unplug'
|
||||
Assert (-not $removed) 'removed a still-attached driver'
|
||||
$script:unplugs++
|
||||
$script:present = $false
|
||||
}
|
||||
Assert ($removed -and $unplugs -eq 2 -and $null -eq $saved) 'timed-out cleanup could not be retried'
|
||||
Assert ($values.LowerFilters.Value[0] -ceq 'external-lower-filter') 'rollback changed an untouched filter'
|
||||
|
||||
Reset-Fixture
|
||||
$script:stack = @()
|
||||
Wait-ForFilterRelease $journal { $script:unplugs++; $script:present = $false }
|
||||
Assert ($unplugs -eq 1) 'unknown live stack treated as proof of detachment'
|
||||
|
||||
Set-Item Function:Remove-OwnedDriver $realRemove
|
||||
$script:service = @{ Type = 1; Start = 3; ImagePath = 'System32\drivers\foreign.sys' }
|
||||
$script:foreignUse = $false
|
||||
$script:stopped = $false
|
||||
$script:deleted = $false
|
||||
function Read-FilterService { $script:service }
|
||||
function Assert-ExclusiveUse($Journal) { if ($script:foreignUse) { throw 'fixture shared filter' } }
|
||||
function Remove-FilterService { $script:stopped = $true; $script:service = $null }
|
||||
function Remove-SessionImage($Journal) { $script:deleted = $true }
|
||||
Expect-Failure { Remove-OwnedDriver $journal } '*another installation*'
|
||||
Assert (-not $stopped -and -not $deleted) 'touched a foreign service'
|
||||
$service.ImagePath = Get-ImagePath $journal
|
||||
$script:foreignUse = $true
|
||||
Expect-Failure { Remove-OwnedDriver $journal } '*shared filter*'
|
||||
Assert (-not $stopped -and -not $deleted) 'removed a shared service'
|
||||
$script:foreignUse = $false
|
||||
Remove-OwnedDriver $journal
|
||||
Remove-OwnedDriver $journal
|
||||
Assert ($stopped -and $deleted) 'could not replay owned removal'
|
||||
|
||||
Write-Output 'Windows iPad Air M3 manual-replug transaction fixtures passed.'
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Exercise the Air M3 frontend against QEMU with a synthetic USB device."""
|
||||
import argparse
|
||||
from contextlib import suppress
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from tempfile import TemporaryDirectory
|
||||
from threading import Event, Thread
|
||||
from time import monotonic, sleep
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from attach import bridge, main
|
||||
|
||||
|
||||
class Fixture:
|
||||
descriptor = bytes.fromhex("12 01 00 02 00 00 00 40 34 12 78 56 00 01 00 00 00 01")
|
||||
configuration = bytes.fromhex("09 02 12 00 01 01 00 80 32 09 04 00 00 00 ff 00 00 00")
|
||||
speed = 2
|
||||
|
||||
def __init__(self):
|
||||
self.config = 0
|
||||
self.alternates = {}
|
||||
self.announced = Event()
|
||||
self.descriptor_read = False
|
||||
|
||||
def layout(self):
|
||||
self.announced.set()
|
||||
return [(0, 0xff, 0, 0)], []
|
||||
|
||||
def control(self, setup, outgoing):
|
||||
request_type, request, value, _, length = setup
|
||||
if (request_type, request, value) == (0x80, 6, 0x0100):
|
||||
self.descriptor_read = True
|
||||
return self.descriptor[:length]
|
||||
if (request_type, request, value) == (0x80, 6, 0x0200):
|
||||
return self.configuration[:length]
|
||||
if (request_type, request) == (0, 9) and value in (0, 1):
|
||||
self.config = value
|
||||
return len(outgoing)
|
||||
raise OSError("synthetic device stalls this USB request")
|
||||
|
||||
|
||||
def check(qemu, firmware, relay, env, accelerator):
|
||||
listing = subprocess.run([str(qemu), "-device", "help"], env=env, text=True,
|
||||
capture_output=True, timeout=10, check=True)
|
||||
for model in ("usb-redir", "reims-graphics-pci"):
|
||||
if not re.search(r'^name "' + re.escape(model) + '"', listing.stdout, re.MULTILINE):
|
||||
raise RuntimeError(f"QEMU does not list {model}")
|
||||
print("QEMU lists usb-redir and reims-graphics-pci.", flush=True)
|
||||
|
||||
with TemporaryDirectory(prefix="reims-usb-") as directory:
|
||||
root = Path(directory)
|
||||
socket_path = root / "qmp.sock"
|
||||
command = [
|
||||
str(qemu), "-L", str(firmware), "-machine", f"q35,accel={accelerator}",
|
||||
"-m", "128", "-nodefaults", "-no-user-config", "-display", "none", "-serial", "none",
|
||||
"-monitor", "none", "-qmp", f"unix:{socket_path},server=on,wait=off",
|
||||
"-S", "-device", "qemu-xhci,id=xhci",
|
||||
]
|
||||
with subprocess.Popen(command, env=env, stdout=subprocess.DEVNULL,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW) as process:
|
||||
try:
|
||||
(root / "qemu.pid").write_text(str(process.pid))
|
||||
deadline = monotonic() + 10
|
||||
while not socket_path.exists():
|
||||
if process.poll() is not None or monotonic() >= deadline:
|
||||
raise RuntimeError("The synthetic guest did not open its QMP socket")
|
||||
sleep(0.1)
|
||||
selected = []
|
||||
|
||||
def accept_guest(guest, _directory):
|
||||
selected.append(guest)
|
||||
return True
|
||||
|
||||
with patch("attach.run", side_effect=accept_guest):
|
||||
if main(["--vm-dir", str(root), "--driver-dir", str(root), "--relay", str(relay)]) != 0:
|
||||
raise RuntimeError("The helper could not open the running guest's QMP path")
|
||||
guest = selected[0]
|
||||
with guest.monitor() as qmp:
|
||||
qmp.call("cont")
|
||||
|
||||
fixture = Fixture()
|
||||
busy_probe = Event()
|
||||
proven = Event()
|
||||
|
||||
def verify_qmp_is_available():
|
||||
if fixture.announced.wait(8):
|
||||
sleep(0.7)
|
||||
with suppress(OSError, RuntimeError), guest.monitor() as qmp:
|
||||
if qmp.call("query-status")["running"]:
|
||||
proven.set()
|
||||
busy_probe.set()
|
||||
|
||||
reader = Thread(target=verify_qmp_is_available, daemon=True)
|
||||
reader.start()
|
||||
deadline = monotonic() + 14
|
||||
bridge(guest, fixture, lambda: not busy_probe.is_set() and monotonic() < deadline)
|
||||
if not (fixture.announced.is_set() and proven.is_set()):
|
||||
raise RuntimeError("The forwarder did not negotiate or the guest monitor stayed busy")
|
||||
with guest.monitor() as qmp:
|
||||
if any(item["name"].startswith("ipad-") for item in qmp.call("qom-list", path="/machine/peripheral")):
|
||||
raise RuntimeError("The USB device was not removed")
|
||||
if any(item["label"].startswith("ipad-char-") for item in qmp.call("query-chardev")):
|
||||
raise RuntimeError("The USB chardev was not removed")
|
||||
qmp.call("quit")
|
||||
if process.wait(timeout=6) != 0:
|
||||
raise RuntimeError("The test guest did not exit normally")
|
||||
print("Synthetic USB handshake, concurrent monitor access, and session cleanup passed.")
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait(timeout=6)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--qemu", type=Path, required=True)
|
||||
parser.add_argument("--firmware-dir", type=Path, required=True)
|
||||
parser.add_argument("--relay", type=Path, required=True)
|
||||
parser.add_argument("--accel", choices=("whpx", "tcg"), default="whpx")
|
||||
args = parser.parse_args()
|
||||
environment = dict(os.environ, PATH="")
|
||||
check(args.qemu.resolve(strict=True), args.firmware_dir.resolve(strict=True),
|
||||
args.relay.resolve(strict=True), environment, args.accel)
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Check how short physical USB sessions report the enumeration result."""
|
||||
from contextlib import nullcontext
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from attach import bridge
|
||||
|
||||
|
||||
class ImmediateExporter:
|
||||
def __init__(self, target):
|
||||
self.target = target
|
||||
|
||||
def start(self):
|
||||
self.target()
|
||||
|
||||
def is_alive(self):
|
||||
return False
|
||||
|
||||
def join(self):
|
||||
pass
|
||||
|
||||
|
||||
class ShortSessionTest(unittest.TestCase):
|
||||
def bridge_with_short_session(self, read_descriptor):
|
||||
device = SimpleNamespace(descriptor_read=False)
|
||||
guest = SimpleNamespace(monitor=lambda: nullcontext(Mock()))
|
||||
|
||||
def export_then_disconnect(_listener, _guest, device, _done, _present):
|
||||
device.descriptor_read = read_descriptor
|
||||
|
||||
with patch("attach.Thread", ImmediateExporter), \
|
||||
patch("attach.export_device", side_effect=export_then_disconnect), \
|
||||
patch("attach.remove_guest_device") as cleanup:
|
||||
try:
|
||||
return bridge(guest, device, lambda: True)
|
||||
finally:
|
||||
cleanup.assert_called_once()
|
||||
|
||||
def test_read_before_mode_change_remains_successful(self):
|
||||
self.assertTrue(self.bridge_with_short_session(read_descriptor=True))
|
||||
|
||||
def test_no_read_or_attachment_reports_timeout(self):
|
||||
with self.assertRaises(TimeoutError):
|
||||
self.bridge_with_short_session(read_descriptor=False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Exercise the same wire protocol as QEMU's usb-redir device."""
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import threading
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
HEADER = struct.Struct("<IIQ")
|
||||
HELLO = struct.pack("<III64sI", 0, 68, 0, b"QEMU test", 0x72)
|
||||
CTRL = struct.Struct("<BBBBHHH")
|
||||
BULK = struct.Struct("<BBHIH")
|
||||
|
||||
|
||||
def exact(peer, length):
|
||||
buf = bytearray()
|
||||
while len(buf) < length:
|
||||
chunk = peer.recv(length - len(buf))
|
||||
if not chunk:
|
||||
raise EOFError
|
||||
buf.extend(chunk)
|
||||
return bytes(buf)
|
||||
|
||||
|
||||
def packet(peer):
|
||||
op, length, seq = HEADER.unpack(exact(peer, 16))
|
||||
return op, seq, exact(peer, length)
|
||||
|
||||
|
||||
class Tablet:
|
||||
descriptor = bytes.fromhex("12 01 00 02 00 00 00 40 ac 05 ab 12 11 07 01 02 03 05")
|
||||
speed = 2
|
||||
config = 5
|
||||
alternates = {}
|
||||
|
||||
def __init__(self):
|
||||
self.reading = threading.Event()
|
||||
self.cancelled = threading.Event()
|
||||
|
||||
def layout(self):
|
||||
return [(2, 2, 13, 0)], [(0x81, 2, 0, 2, 512), (0x02, 2, 0, 2, 512)]
|
||||
|
||||
def control(self, setup, outgoing):
|
||||
if setup == (0xa1, 0x80, 0, 2, 28):
|
||||
return bytes(range(28))
|
||||
if setup == (0, 9, 5, 0, 0):
|
||||
return 0
|
||||
raise OSError("stalled")
|
||||
|
||||
def transfer(self, address, length, data, flags, cancel):
|
||||
if address == 0x81:
|
||||
self.reading.set()
|
||||
if not cancel.wait(2):
|
||||
raise OSError("read did not get cancelled")
|
||||
self.cancelled.set()
|
||||
return b""
|
||||
return len(data)
|
||||
|
||||
|
||||
class ControlEndpointSizeTest(unittest.TestCase):
|
||||
def test_usbredir_advertises_control_endpoint_size_in_bytes(self):
|
||||
from usb_redir import Session
|
||||
|
||||
for speed, descriptor_size, expected_size in ((2, 64, 64), (3, 9, 512)):
|
||||
with self.subTest(speed=speed):
|
||||
tablet = Tablet()
|
||||
tablet.speed = speed
|
||||
descriptor = bytearray(tablet.descriptor)
|
||||
descriptor[7] = descriptor_size
|
||||
tablet.descriptor = bytes(descriptor)
|
||||
peer = Mock()
|
||||
Session(peer, tablet).topology()
|
||||
message = peer.sendall.call_args_list[0].args[0]
|
||||
sizes = struct.unpack_from("<32H", message, HEADER.size + 96)
|
||||
self.assertEqual((sizes[0], sizes[16]), (expected_size, expected_size))
|
||||
|
||||
|
||||
class InterruptCleanupTest(unittest.TestCase):
|
||||
def test_disconnect_during_interrupt_ack_still_closes_workers(self):
|
||||
from usb_redir import Op, Session
|
||||
|
||||
tablet = Tablet()
|
||||
tablet.layout = lambda: ([(2, 2, 13, 0)], [(0x81, 3, 1, 2, 64)])
|
||||
peer = Mock()
|
||||
peer.sendall.side_effect = ConnectionError("guest disconnected")
|
||||
session = Session(peer, tablet)
|
||||
worker = Mock()
|
||||
session.workers[1] = worker
|
||||
|
||||
with self.assertRaises(ConnectionError):
|
||||
session.interrupt(Op.START_INTERRUPT, 1, 0x81)
|
||||
session.close()
|
||||
|
||||
self.assertFalse(session.interrupts)
|
||||
worker.shutdown.assert_called_once_with(wait=True, cancel_futures=True)
|
||||
|
||||
|
||||
class RedirectionTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.assertIsNotNone(importlib.util.find_spec("usb_redir"), "usbredir exporter is missing")
|
||||
from usb_redir import serve
|
||||
self.tablet = Tablet()
|
||||
self.client, server = socket.socketpair()
|
||||
self.client.settimeout(3)
|
||||
def run():
|
||||
with server:
|
||||
serve(server, self.tablet, lambda: False)
|
||||
self.thread = threading.Thread(target=run)
|
||||
self.thread.start()
|
||||
self.client.sendall(HELLO)
|
||||
hello = exact(self.client, 80)
|
||||
self.assertEqual(struct.unpack_from("<III", hello), (0, 68, 0))
|
||||
ep, intf, connected = (packet(self.client) for _ in range(3))
|
||||
self.assertEqual([ep[0], intf[0], connected[0]], [5, 4, 1])
|
||||
self.assertEqual(ep[2][17], 2)
|
||||
self.assertEqual(intf[2][:5], bytes((1, 0, 0, 0, 2)))
|
||||
self.assertEqual(connected[2], bytes.fromhex("02 00 00 00 ac 05 ab 12 11 07"))
|
||||
|
||||
def tearDown(self):
|
||||
if hasattr(self, "client"):
|
||||
self.client.close()
|
||||
self.thread.join(3)
|
||||
self.assertFalse(self.thread.is_alive())
|
||||
|
||||
def send(self, op, seq, data):
|
||||
self.client.sendall(HEADER.pack(op, len(data), seq) + data)
|
||||
|
||||
def test_ncm_control_data_and_configuration(self):
|
||||
self.send(6, 1, b"\x05")
|
||||
self.assertEqual([packet(self.client)[0] for _ in range(2)], [5, 4])
|
||||
self.assertEqual(packet(self.client), (8, 1, b"\x00\x05"))
|
||||
ctrl = CTRL.pack(0x80, 0x80, 0xa1, 0, 0, 2, 28)
|
||||
self.send(100, 2, ctrl)
|
||||
self.assertEqual(packet(self.client), (100, 2, ctrl + bytes(range(28))))
|
||||
|
||||
def test_pending_read_does_not_block_write_or_cancel(self):
|
||||
self.send(101, 7, BULK.pack(0x81, 0, 512, 0, 0))
|
||||
self.assertTrue(self.tablet.reading.wait(2))
|
||||
out = BULK.pack(2, 0, 3, 0, 0)
|
||||
self.send(101, 8, out + b"abc")
|
||||
self.assertEqual(packet(self.client), (101, 8, out))
|
||||
self.send(21, 7, b"")
|
||||
self.assertEqual(packet(self.client), (101, 7, BULK.pack(0x81, 1, 0, 0, 0)))
|
||||
self.assertTrue(self.tablet.cancelled.is_set())
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Switch the tested iPad into NCM mode and pass transfers to its signed filter."""
|
||||
|
||||
from array import array
|
||||
from contextlib import contextmanager
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from threading import Lock
|
||||
|
||||
import usb.backend.libusb0
|
||||
import usb.core
|
||||
import usb.util
|
||||
|
||||
|
||||
IPAD = (0x05AC, 0x12AB)
|
||||
REVISION = 0x1503
|
||||
# User-mode library in libusb-win32-bin-1.4.0.2/bin/amd64.
|
||||
DLL_SHA256 = "0cd18719d5701e9cc642fc93a83f13830931d6f29f664fedbdf212bcb7c349bd"
|
||||
|
||||
|
||||
def backend_from(directory):
|
||||
path = directory / "libusb0.dll"
|
||||
if hashlib.sha256(path.read_bytes()).hexdigest() != DLL_SHA256:
|
||||
raise ValueError("select the amd64 directory from libusb-win32 1.4.0.2")
|
||||
backend = usb.backend.libusb0.get_backend(find_library=lambda _: str(path))
|
||||
if backend is None:
|
||||
raise OSError("could not load libusb0.dll with this Python interpreter")
|
||||
return backend
|
||||
|
||||
|
||||
def filtered_ipad(backend, expected_count):
|
||||
matches = []
|
||||
for raw in backend.enumerate_devices():
|
||||
descriptor = backend.get_device_descriptor(raw)
|
||||
if (descriptor.idVendor, descriptor.idProduct) == IPAD:
|
||||
matches.append((raw, descriptor))
|
||||
if len(matches) != 1:
|
||||
raise OSError("The temporary filter did not expose exactly one iPad")
|
||||
raw, descriptor = matches[0]
|
||||
if descriptor.bcdDevice != REVISION or descriptor.bNumConfigurations != expected_count:
|
||||
raise OSError("The filtered iPad does not match the USB hub descriptor")
|
||||
return raw, usb.core.Device(raw, backend)
|
||||
|
||||
|
||||
class Ipad:
|
||||
def __init__(self, backend, info):
|
||||
self.backend = backend
|
||||
self.raw, self.dev = filtered_ipad(backend, info.count)
|
||||
self.descriptor = info.descriptor
|
||||
self.speed = info.speed - 1 # usbredir uses Windows' zero-based speed values
|
||||
self.config = info.config
|
||||
self.lock = Lock()
|
||||
self.handles = {}
|
||||
self.alternates = {}
|
||||
self.in_flight = 0
|
||||
self.control_handle = backend.open_device(self.raw)
|
||||
try:
|
||||
backend.set_configuration(self.control_handle, self.config)
|
||||
except BaseException:
|
||||
backend.close_device(self.control_handle)
|
||||
raise
|
||||
|
||||
def layout(self):
|
||||
interfaces, endpoints = [], []
|
||||
config = usb.util.find_descriptor(self.dev, bConfigurationValue=self.config)
|
||||
if config is not None:
|
||||
for intf in config:
|
||||
index = intf.bInterfaceNumber
|
||||
if intf.bAlternateSetting != self.alternates.get(index, 0):
|
||||
continue
|
||||
interfaces.append((index, intf.bInterfaceClass, intf.bInterfaceSubClass, intf.bInterfaceProtocol))
|
||||
for ep in intf:
|
||||
endpoints.append((ep.bEndpointAddress, ep.bmAttributes & 3, ep.bInterval,
|
||||
index, ep.wMaxPacketSize & 0x7ff))
|
||||
return interfaces, endpoints
|
||||
|
||||
def handle(self, interface):
|
||||
if interface not in self.handles:
|
||||
handle = self.backend.open_device(self.raw)
|
||||
try:
|
||||
self.backend.set_configuration(handle, self.config)
|
||||
self.backend.claim_interface(handle, interface)
|
||||
except BaseException:
|
||||
self.backend.close_device(handle)
|
||||
raise
|
||||
self.handles[interface] = handle
|
||||
return self.handles[interface]
|
||||
|
||||
def release_interfaces(self):
|
||||
handles, self.handles = self.handles, {}
|
||||
self.alternates.clear()
|
||||
error = None
|
||||
for handle in handles.values():
|
||||
try:
|
||||
self.backend.close_device(handle)
|
||||
except OSError as exc:
|
||||
error = exc
|
||||
if error:
|
||||
raise error
|
||||
|
||||
def close(self):
|
||||
try:
|
||||
self.release_interfaces()
|
||||
finally:
|
||||
self.backend.close_device(self.control_handle)
|
||||
|
||||
def control(self, setup, data):
|
||||
kind, request, value, index, length = setup
|
||||
if (kind, request) == (0, 9):
|
||||
with self.lock:
|
||||
if value != self.config:
|
||||
if self.in_flight:
|
||||
raise OSError("configuration changed with transfers in flight")
|
||||
self.release_interfaces()
|
||||
self.backend.set_configuration(self.control_handle, value)
|
||||
self.config = value
|
||||
return 0
|
||||
if (kind, request) == (1, 11):
|
||||
with self.lock:
|
||||
self.backend.set_interface_altsetting(self.handle(index), index, value)
|
||||
self.alternates[index] = value
|
||||
return 0
|
||||
buf = usb.util.create_buffer(length) if kind & 0x80 else array("B", data)
|
||||
size = self.backend.ctrl_transfer(self.control_handle, kind, request, value, index, buf, 1500)
|
||||
return buf[:size].tobytes() if kind & 0x80 else size
|
||||
|
||||
@contextmanager
|
||||
def endpoint(self, address):
|
||||
with self.lock:
|
||||
cfg = usb.util.find_descriptor(self.dev, bConfigurationValue=self.config)
|
||||
if cfg is None:
|
||||
raise OSError("the iPad has no active USB configuration")
|
||||
for interface in cfg:
|
||||
index = interface.bInterfaceNumber
|
||||
if interface.bAlternateSetting != self.alternates.get(index, 0):
|
||||
continue
|
||||
ep = usb.util.find_descriptor(interface, bEndpointAddress=address)
|
||||
if ep is not None:
|
||||
handle = self.handle(index)
|
||||
break
|
||||
else:
|
||||
raise OSError("endpoint is not active")
|
||||
self.in_flight += 1
|
||||
try:
|
||||
yield handle, index, ep
|
||||
finally:
|
||||
with self.lock:
|
||||
self.in_flight -= 1
|
||||
|
||||
def transfer(self, address, length, outgoing, flags, cancelled):
|
||||
with self.endpoint(address) as (handle, interface, ep):
|
||||
kind = ep.bmAttributes & 3
|
||||
if kind not in (2, 3):
|
||||
raise NotImplementedError("only bulk and interrupt endpoints are supported")
|
||||
if address & 0x80:
|
||||
read = self.backend.bulk_read if kind == 2 else self.backend.intr_read
|
||||
data = usb.util.create_buffer(length)
|
||||
while not cancelled.is_set():
|
||||
try:
|
||||
got = read(handle, address, interface, data, 350)
|
||||
return data[:got].tobytes()
|
||||
except usb.core.USBError as exc:
|
||||
if (getattr(exc, "backend_error_code", None) not in (-110, -116)
|
||||
and not isinstance(exc, usb.core.USBTimeoutError)):
|
||||
raise
|
||||
return b""
|
||||
write = self.backend.bulk_write if kind == 2 else self.backend.intr_write
|
||||
got = write(handle, address, interface, array("B", outgoing), 1000)
|
||||
packet = ep.wMaxPacketSize & 0x7ff
|
||||
if flags & 0x40 and packet and got == length and got and got % packet == 0:
|
||||
write(handle, address, interface, array("B"), 1000)
|
||||
return got
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Read the connection and descriptors of a selected port through its Windows hub."""
|
||||
|
||||
import ctypes as ct
|
||||
from ctypes import wintypes as wt
|
||||
from dataclasses import dataclass
|
||||
import struct
|
||||
from uuid import UUID
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Connection:
|
||||
descriptor: bytes
|
||||
config: int
|
||||
speed: int
|
||||
address: int
|
||||
|
||||
@property
|
||||
def ids(self):
|
||||
return struct.unpack_from("<HH", self.descriptor, 8)
|
||||
|
||||
@property
|
||||
def count(self):
|
||||
return self.descriptor[17]
|
||||
|
||||
@classmethod
|
||||
def decode(cls, data):
|
||||
# USB_NODE_CONNECTION_INFORMATION_EX (usbioctl.h). Windows speed starts
|
||||
# at zero for low speed. USB/IP starts at one.
|
||||
if len(data) < 35:
|
||||
raise ValueError("short USB hub connection record")
|
||||
if struct.unpack_from("<I", data, 31)[0] != 1:
|
||||
return None
|
||||
if data[4:6] != b"\x12\x01":
|
||||
raise ValueError("invalid device descriptor")
|
||||
return cls(bytes(data[4:22]), data[22], data[23] + 1, struct.unpack_from("<H", data, 25)[0])
|
||||
|
||||
|
||||
class Hub:
|
||||
def __init__(self, instance, port):
|
||||
self.port = port
|
||||
cm = ct.WinDLL("CfgMgr32", use_last_error=True)
|
||||
self.kernel = ct.WinDLL("Kernel32", use_last_error=True)
|
||||
guid = (ct.c_byte * 16).from_buffer_copy(UUID("f18a0e88-c30c-11d0-8815-00a0c906bed8").bytes_le)
|
||||
cm.CM_Get_Device_Interface_List_SizeW.argtypes = (ct.POINTER(wt.ULONG), ct.c_void_p, wt.LPCWSTR, wt.ULONG)
|
||||
cm.CM_Get_Device_Interface_ListW.argtypes = (ct.c_void_p, wt.LPCWSTR, wt.LPWSTR, wt.ULONG, wt.ULONG)
|
||||
length = wt.ULONG()
|
||||
if cm.CM_Get_Device_Interface_List_SizeW(ct.byref(length), ct.byref(guid), instance, 0) or length.value < 2:
|
||||
raise OSError("cannot locate the selected iPad's USB hub")
|
||||
paths = ct.create_unicode_buffer(length.value)
|
||||
if cm.CM_Get_Device_Interface_ListW(ct.byref(guid), instance, paths, length.value, 0) or not paths.value:
|
||||
raise OSError("cannot open the selected iPad's USB hub interface")
|
||||
self.kernel.CreateFileW.argtypes = (wt.LPCWSTR, wt.DWORD, wt.DWORD, ct.c_void_p, wt.DWORD, wt.DWORD, wt.HANDLE)
|
||||
self.kernel.CreateFileW.restype = wt.HANDLE
|
||||
self.kernel.DeviceIoControl.argtypes = (wt.HANDLE, wt.DWORD, ct.c_void_p, wt.DWORD, ct.c_void_p,
|
||||
wt.DWORD, ct.POINTER(wt.DWORD), ct.c_void_p)
|
||||
self.kernel.CloseHandle.argtypes = (wt.HANDLE,)
|
||||
self.handle = self.kernel.CreateFileW(paths.value, 0, 3, None, 3, 0, None)
|
||||
if self.handle == ct.c_void_p(-1).value:
|
||||
raise ct.WinError(ct.get_last_error())
|
||||
|
||||
def close(self):
|
||||
self.kernel.CloseHandle(self.handle)
|
||||
|
||||
def query(self, function, prefix, size):
|
||||
buffer = ct.create_string_buffer(size)
|
||||
ct.memmove(buffer, prefix, len(prefix))
|
||||
received = wt.DWORD()
|
||||
code = (0x22 << 16) | (function << 2)
|
||||
if not self.kernel.DeviceIoControl(self.handle, code, buffer, size, buffer, size, ct.byref(received), None):
|
||||
raise ct.WinError(ct.get_last_error())
|
||||
return buffer.raw[:received.value]
|
||||
|
||||
def connection(self):
|
||||
data = self.query(274, struct.pack("<I", self.port), 4096)
|
||||
return Connection.decode(data)
|
||||
|
||||
def configuration(self, index):
|
||||
def read(length):
|
||||
request = struct.pack("<IBBHHH", self.port, 0x80, 6, 0x0200 | index, 0, length)
|
||||
return self.query(260, request, len(request) + length)[len(request):]
|
||||
header = read(9)
|
||||
if len(header) != 9 or header[:2] != b"\x09\x02":
|
||||
raise ValueError("invalid USB configuration header")
|
||||
size = struct.unpack_from("<H", header, 2)[0]
|
||||
if size < 9:
|
||||
raise ValueError("incomplete USB configuration")
|
||||
return read(size)
|
||||
@@ -0,0 +1,288 @@
|
||||
"""Host end of the usbredir 0.7 protocol for the iPad's development interfaces."""
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from enum import IntEnum
|
||||
import struct
|
||||
from threading import Event, Lock, Thread
|
||||
import time
|
||||
|
||||
|
||||
class Op(IntEnum):
|
||||
HELLO = 0
|
||||
CONNECT = 1
|
||||
DISCONNECT = 2
|
||||
RESET = 3
|
||||
INTERFACES = 4
|
||||
ENDPOINTS = 5
|
||||
SET_CONFIG = 6
|
||||
GET_CONFIG = 7
|
||||
CONFIG = 8
|
||||
SET_ALT = 9
|
||||
GET_ALT = 10
|
||||
ALT = 11
|
||||
START_INTERRUPT = 15
|
||||
STOP_INTERRUPT = 16
|
||||
INTERRUPT_STATUS = 17
|
||||
CANCEL = 21
|
||||
CONTROL = 100
|
||||
BULK = 101
|
||||
INTERRUPT = 103
|
||||
|
||||
|
||||
SHORT = struct.Struct("<III") # Initial hello uses 32-bit IDs.
|
||||
HEADER = struct.Struct("<IIQ")
|
||||
CONTROL = struct.Struct("<BBBBHHH")
|
||||
BULK = struct.Struct("<BBHIH")
|
||||
INTERRUPT = struct.Struct("<BBH")
|
||||
# Device version, endpoint packet sizes, 64-bit IDs and 32-bit bulk lengths.
|
||||
CAPABILITIES = 0x72
|
||||
MAX_TRANSFER = 16 << 20
|
||||
MAX_PENDING_BYTES = 32 << 20
|
||||
|
||||
|
||||
def receive(peer, size, stopped):
|
||||
buf = bytearray()
|
||||
while len(buf) < size:
|
||||
if stopped():
|
||||
raise EOFError
|
||||
try:
|
||||
part = peer.recv(size - len(buf))
|
||||
except TimeoutError:
|
||||
continue
|
||||
if not part:
|
||||
raise EOFError
|
||||
buf.extend(part)
|
||||
return bytes(buf)
|
||||
|
||||
|
||||
class Session:
|
||||
def __init__(self, peer, device):
|
||||
self.peer = peer
|
||||
self.device = device
|
||||
self.pending = {}
|
||||
self.queued_bytes = 0
|
||||
self.workers = {}
|
||||
self.interrupts = {}
|
||||
self.lock = Lock()
|
||||
self.writes = Lock()
|
||||
self.closed = Event()
|
||||
|
||||
def send(self, op, seq, payload=b""):
|
||||
with self.writes:
|
||||
self.peer.sendall(HEADER.pack(op, len(payload), seq) + payload)
|
||||
|
||||
def topology(self):
|
||||
interfaces, endpoints = self.device.layout()
|
||||
kinds = bytearray([255] * 32)
|
||||
owners = bytearray([255] * 32)
|
||||
intervals = bytearray(32)
|
||||
sizes = [0] * 32
|
||||
control_size = self.device.descriptor[7]
|
||||
if self.device.speed == 3: # usbredir SuperSpeed
|
||||
# USB 3 encodes bMaxPacketSize0 as an exponent. usbredir sends bytes.
|
||||
if control_size != 9:
|
||||
raise ValueError("invalid SuperSpeed control endpoint size")
|
||||
control_size = 1 << control_size
|
||||
for slot in (0, 16):
|
||||
kinds[slot] = 0
|
||||
sizes[slot] = control_size
|
||||
for address, kind, interval, interface, size in endpoints:
|
||||
slot = (address & 15) + (16 if address & 0x80 else 0)
|
||||
kinds[slot], intervals[slot], owners[slot], sizes[slot] = kind, interval, interface, size
|
||||
self.send(Op.ENDPOINTS, 0, kinds + intervals + owners + struct.pack("<32H", *sizes))
|
||||
columns = [bytearray(32) for _ in range(4)]
|
||||
for i, values in enumerate(interfaces):
|
||||
for column, value in zip(columns, values):
|
||||
column[i] = value
|
||||
self.send(Op.INTERFACES, 0, struct.pack("<I", len(interfaces)) + b"".join(columns))
|
||||
|
||||
def announce(self):
|
||||
self.topology()
|
||||
desc = self.device.descriptor
|
||||
identity = bytes([self.device.speed]) + desc[4:7] + desc[8:14]
|
||||
self.send(Op.CONNECT, 0, identity)
|
||||
|
||||
def dispatch(self, op, seq, body):
|
||||
if op in (Op.CONTROL, Op.BULK, Op.INTERRUPT):
|
||||
self.submit(op, seq, body)
|
||||
elif op == Op.CANCEL:
|
||||
with self.lock:
|
||||
if seq in self.pending:
|
||||
self.pending[seq].set()
|
||||
elif op in (Op.GET_CONFIG, Op.SET_CONFIG, Op.GET_ALT, Op.SET_ALT):
|
||||
self.configure(op, seq, body)
|
||||
elif op in (Op.START_INTERRUPT, Op.STOP_INTERRUPT):
|
||||
endpoint, = struct.unpack("B", body)
|
||||
self.interrupt(op, seq, endpoint)
|
||||
elif op == Op.RESET:
|
||||
# Cycling this iPad's physical port loses configuration 5. Drop
|
||||
# queued endpoint I/O; the guest will select the USB settings again.
|
||||
self.cancel_all()
|
||||
else:
|
||||
raise ValueError(f"unsupported usbredir packet {op}")
|
||||
|
||||
def configure(self, op, seq, body):
|
||||
dev = self.device
|
||||
if op in (Op.SET_CONFIG, Op.GET_CONFIG):
|
||||
status = 0
|
||||
if op == Op.SET_CONFIG:
|
||||
config, = struct.unpack("B", body)
|
||||
try:
|
||||
dev.control((0, 9, config, 0, 0), b"")
|
||||
self.topology()
|
||||
except (ValueError, OSError):
|
||||
status = 4
|
||||
self.send(Op.CONFIG, seq, bytes((status, dev.config)))
|
||||
else:
|
||||
status = 0
|
||||
if op == Op.SET_ALT:
|
||||
index, alt = struct.unpack("BB", body)
|
||||
try:
|
||||
dev.control((1, 11, alt, index, 0), b"")
|
||||
self.topology()
|
||||
except (ValueError, OSError):
|
||||
status = 4
|
||||
else:
|
||||
index, = struct.unpack("B", body)
|
||||
self.send(Op.ALT, seq, bytes((status, index, dev.alternates.get(index, 0))))
|
||||
|
||||
def submit(self, op, seq, body):
|
||||
fmt = {Op.CONTROL: CONTROL, Op.BULK: BULK, Op.INTERRUPT: INTERRUPT}[op]
|
||||
fields = list(fmt.unpack_from(body))
|
||||
endpoint = fields[0]
|
||||
if endpoint & 0x70 or (op != Op.CONTROL and endpoint & 15 == 0):
|
||||
raise ValueError("invalid USB endpoint")
|
||||
if op == Op.CONTROL:
|
||||
_, request, kind, _, value, index, length = fields
|
||||
if endpoint != (kind & 0x80):
|
||||
raise ValueError("inconsistent control direction")
|
||||
setup = (kind, request, value, index, length)
|
||||
elif op == Op.BULK:
|
||||
length = fields[2] | fields[4] << 16
|
||||
if fields[3]:
|
||||
raise ValueError("bulk streams are unavailable on this iPad")
|
||||
setup = None
|
||||
else:
|
||||
length = fields[2]
|
||||
setup = None
|
||||
incoming = bool(endpoint & 0x80)
|
||||
data = body[fmt.size:]
|
||||
if length > MAX_TRANSFER or len(data) != (0 if incoming else length):
|
||||
raise ValueError("invalid USB transfer length")
|
||||
with self.lock:
|
||||
if seq in self.pending or len(self.pending) >= 256 or self.queued_bytes + length > MAX_PENDING_BYTES:
|
||||
raise ValueError("usbredir transfer queue limit or duplicate ID")
|
||||
cancelled = self.pending[seq] = Event()
|
||||
self.queued_bytes += length
|
||||
slot = 0 if op == Op.CONTROL else endpoint
|
||||
if slot not in self.workers:
|
||||
self.workers[slot] = ThreadPoolExecutor(max_workers=1)
|
||||
|
||||
def complete():
|
||||
actual = status = 0
|
||||
payload = b""
|
||||
try:
|
||||
if not cancelled.is_set():
|
||||
result = (self.device.control(setup, data) if setup is not None
|
||||
else self.device.transfer(endpoint, length, data, 0, cancelled))
|
||||
actual = len(result) if incoming else result
|
||||
if actual < 0 or actual > length:
|
||||
raise ValueError("invalid completion size")
|
||||
if incoming:
|
||||
payload = result
|
||||
except (OSError, ValueError, NotImplementedError):
|
||||
status, actual, payload = 4, 0, b"" # STALL
|
||||
with self.lock:
|
||||
try:
|
||||
if cancelled.is_set():
|
||||
status, actual, payload = 1, 0, b""
|
||||
if op == Op.CONTROL:
|
||||
fields[3], fields[6] = status, actual
|
||||
elif op == Op.BULK:
|
||||
fields[1], fields[2], fields[4] = status, actual & 0xffff, actual >> 16
|
||||
else:
|
||||
fields[1], fields[2] = status, actual
|
||||
if not self.closed.is_set():
|
||||
self.send(op, seq, fmt.pack(*fields) + payload)
|
||||
except OSError:
|
||||
self.closed.set()
|
||||
finally:
|
||||
del self.pending[seq]
|
||||
self.queued_bytes -= length
|
||||
self.workers[slot].submit(complete)
|
||||
|
||||
def interrupt(self, op, seq, address):
|
||||
previous = self.interrupts.pop(address, None)
|
||||
if previous:
|
||||
previous[0].set()
|
||||
previous[1].join()
|
||||
if op == Op.STOP_INTERRUPT:
|
||||
self.send(Op.INTERRUPT_STATUS, seq, bytes((0, address)))
|
||||
return
|
||||
_, endpoints = self.device.layout()
|
||||
length = next((size for ep, kind, _, _, size in endpoints
|
||||
if ep == address and kind == 3 and ep & 0x80), 0)
|
||||
if not length:
|
||||
self.send(Op.INTERRUPT_STATUS, seq, bytes((2, address)))
|
||||
return
|
||||
stop = Event()
|
||||
def read():
|
||||
try:
|
||||
while not stop.is_set():
|
||||
data = self.device.transfer(address, length, b"", 0, stop)
|
||||
if not stop.is_set():
|
||||
self.send(Op.INTERRUPT, 0, INTERRUPT.pack(address, 0, len(data)) + data)
|
||||
except (OSError, ValueError):
|
||||
if not stop.is_set() and not self.closed.is_set():
|
||||
try:
|
||||
self.send(Op.INTERRUPT_STATUS, 0, bytes((3, address)))
|
||||
except OSError:
|
||||
self.closed.set()
|
||||
thread = Thread(target=read, name=f"iPad interrupt {address:02x}")
|
||||
self.send(Op.INTERRUPT_STATUS, seq, bytes((0, address)))
|
||||
thread.start()
|
||||
self.interrupts[address] = stop, thread
|
||||
|
||||
def cancel_all(self):
|
||||
with self.lock:
|
||||
for cancel in self.pending.values():
|
||||
cancel.set()
|
||||
for stop, thread in self.interrupts.values():
|
||||
stop.set()
|
||||
thread.join()
|
||||
self.interrupts.clear()
|
||||
|
||||
def close(self):
|
||||
self.closed.set()
|
||||
self.cancel_all()
|
||||
for worker in self.workers.values():
|
||||
worker.shutdown(wait=True, cancel_futures=True)
|
||||
|
||||
|
||||
def serve(peer, device, stopped):
|
||||
session = Session(peer, device)
|
||||
try:
|
||||
# QEMU and the host both send hello using the old 12-byte header first.
|
||||
peer.sendall(SHORT.pack(Op.HELLO, 68, 0) + struct.pack("<64sI", b"reims-ctl", CAPABILITIES))
|
||||
deadline = time.monotonic() + 15
|
||||
def expired():
|
||||
return stopped() or time.monotonic() >= deadline
|
||||
op, size, seq = SHORT.unpack(receive(peer, SHORT.size, expired))
|
||||
if op != Op.HELLO or seq or not 68 <= size <= 256 or size % 4:
|
||||
raise ValueError("invalid usbredir hello")
|
||||
hello = receive(peer, size, expired)
|
||||
caps = struct.unpack_from("<I", hello, 64)[0]
|
||||
if caps & CAPABILITIES != CAPABILITIES:
|
||||
raise ValueError("QEMU lacks required usbredir capabilities")
|
||||
session.announce()
|
||||
def finished():
|
||||
return session.closed.is_set() or stopped()
|
||||
while True:
|
||||
op, length, seq = HEADER.unpack(receive(peer, HEADER.size, finished))
|
||||
if length > MAX_TRANSFER + 16:
|
||||
raise ValueError("usbredir packet exceeds maximum size")
|
||||
session.dispatch(op, seq, receive(peer, length, finished))
|
||||
except (EOFError, ConnectionError):
|
||||
pass
|
||||
finally:
|
||||
session.close()
|
||||
Reference in new issue
Block a user