功能:扩展U盘兼容并优化插拔响应和导出负载

This commit is contained in:
songyiming committed 2026-11-04 19:12:42 +08:00
1 parent b2de05c6a6
commit bb5f554820
9 files changed
+589 -73

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
#!/bin/sh
# Run on the Linux box as its build user. Download headers only; do not upgrade
# system GLib/libusb or overwrite the distribution's /usr/bin/usbredirect.
set -eu
build_root="${1:?usage: build-usbredirect-private.sh ABSOLUTE_NEW_BUILD_DIRECTORY}"
case "$build_root" in /*) ;; *) exit 2 ;; esac
mkdir "$build_root"
cd "$build_root"
mkdir headers
python3 - <<'PY'
import hashlib, pathlib, tarfile, urllib.request
url = 'https://www.spice-space.org/download/usbredir/usbredir-0.15.0.tar.xz'
data = urllib.request.urlopen(url, timeout=60).read()
expected = '6dc2a380277688a068191245dac2ab7063a552999d8ac3ad8e841c10ff050961'
if hashlib.sha256(data).hexdigest() != expected:
raise SystemExit('usbredir source checksum mismatch')
archive = pathlib.Path('usbredir-0.15.0.tar.xz')
archive.write_bytes(data)
with tarfile.open(archive) as tar:
base = pathlib.Path('.').resolve()
for item in tar.getmembers():
if not (base / item.name).resolve().is_relative_to(base) or item.issym() or item.islnk():
raise SystemExit('unexpected archive member')
tar.extractall('.')
PY
# apt validates package hashes from the configured repository metadata. These
# two development packages are extracted into this private directory only.
apt-get download libglib2.0-dev libusb-1.0-0-dev
for package in ./*.deb; do dpkg-deb -x "$package" headers; done
arch=$(cc -print-multiarch)
cat >config.h <<'EOF'
#define PACKAGE_STRING "usbredir 0.15.0"
#define PACKAGE_VERSION "0.15.0"
#define VERSION "0.15.0"
#define PACKAGE_BUGREPORT "https://gitlab.freedesktop.org/spice/usbredir/issues"
#define USBREDIR_VISIBLE __attribute__((visibility("default")))
EOF
source_dir="$build_root/usbredir-0.15.0"
# Static usbredir objects; GLib, libusb and libc remain the installed runtime.
cc -O2 -g -fstack-protector-strong -D_FORTIFY_SOURCE=2 -pthread \
-Wno-deprecated-declarations -I. \
-Iheaders/usr/include/glib-2.0 \
-I"headers/usr/lib/$arch/glib-2.0/include" \
-Iheaders/usr/include/gio-unix-2.0 -Iheaders/usr/include/libusb-1.0 \
-I"$source_dir/usbredirhost" -I"$source_dir/usbredirparser" \
"$source_dir/tools/usbredirect.c" "$source_dir/usbredirhost/usbredirhost.c" \
"$source_dir/usbredirparser/usbredirparser.c" "$source_dir/usbredirparser/usbredirfilter.c" \
"/usr/lib/$arch/libgio-2.0.so.0" "/usr/lib/$arch/libgobject-2.0.so.0" \
"/usr/lib/$arch/libglib-2.0.so.0" "/usr/lib/$arch/libusb-1.0.so.0" \
-o usbredirect
./usbredirect --help
for suite in filter serializer; do
cc -O2 -pthread -I. -Iheaders/usr/include/glib-2.0 \
-I"headers/usr/lib/$arch/glib-2.0/include" -I"$source_dir/usbredirparser" \
"$source_dir/tests/$suite.c" "$source_dir/usbredirparser/usbredirparser.c" \
"$source_dir/usbredirparser/usbredirfilter.c" \
"/usr/lib/$arch/libglib-2.0.so.0" -o "test-$suite"
"./test-$suite"
done
sha256sum usbredirect
+68 -18
View File
@@ -1,10 +1,12 @@
#!/usr/bin/env python3
"""Install a one-device usbredir POC using a restricted SSH tunnel.
"""Install USB Mass Storage redirection using a restricted SSH tunnel.
Requires paramiko on the admin machine and rustc/cargo/usbredirect on the box.
PVE authentication uses SSH keys or VDI_PVE_SSH_PASSWORD (never stored in files).
This prepares services only. Safely unmount the selected USB volume, start the
box service, then run usb-device-qmp.py attach on the PVE node.
Use --any-storage to accept any pure USB Mass Storage device, or provide an
exact VID/PID/serial identity for the legacy single-device policy. The
deployment installs a QMP watcher so the runtime USB endpoint is restored
after a VM/PVE restart.
"""
import argparse
import json
@@ -13,6 +15,7 @@ from pathlib import Path
import re
import shlex
import subprocess
import tempfile
import time
@@ -35,10 +38,16 @@ def pve_run(client, command):
def install(args, password=None):
import paramiko
if not re.fullmatch(r"[0-9a-f]{4}", args.vendor) or not re.fullmatch(r"[0-9a-f]{4}", args.product):
raise ValueError("VID/PID must be four lowercase hex digits")
if not re.fullmatch(r"[A-Za-z0-9_.-]+", args.serial) or not args.serial:
raise ValueError("POC installer supports nonempty alphanumeric serials only")
exact = all(getattr(args, name, None) for name in ("vendor", "product", "serial"))
if args.any_storage and exact:
raise ValueError("--any-storage cannot be combined with an exact device identity")
if not args.any_storage and not exact:
raise ValueError("choose --any-storage or provide --vendor, --product and --serial")
if exact:
if not re.fullmatch(r"[0-9a-f]{4}", args.vendor) or not re.fullmatch(r"[0-9a-f]{4}", args.product):
raise ValueError("VID/PID must be four lowercase hex digits")
if not re.fullmatch(r"[A-Za-z0-9_.-]+", args.serial) or not args.serial:
raise ValueError("installer supports nonempty alphanumeric serials only")
if not re.fullmatch(r"[a-z_][a-z0-9_-]*@[A-Za-z0-9.-]+", args.box):
raise ValueError("invalid box SSH destination")
if args.vm < 100:
@@ -80,12 +89,33 @@ p.chmod(0o600)
f'command="/bin/false" {pubkey}')
box_run(args.box, f"python3 - {shlex.quote(backup)} {shlex.quote(auth_line)}", auth_script)
stage = box_run(args.box, "mktemp -d /tmp/vdi-usb-deploy.XXXXXX").strip()
subprocess.run(["scp", "-q", str(repo / "terminal/usb-monitor/etc/vdi-usb-monitor.service"),
f"{args.box}:{stage}/vdi-usb-monitor.service"], check=True)
env = f'VDI_USB_VENDOR={args.vendor}\nVDI_USB_PRODUCT={args.product}\nVDI_USB_SERIAL={args.serial}\n'
rule = (f'# VDI USB device POC: only the approved device\nSUBSYSTEM=="block", '
f'ATTRS{{idVendor}}=="{args.vendor}", ATTRS{{idProduct}}=="{args.product}", '
f'ATTRS{{serial}}=="{args.serial}", ENV{{UDISKS_IGNORE}}="1"\n')
service_text = (repo / "terminal/usb-monitor/etc/vdi-usb-monitor.service").read_text()
if args.any_storage:
service_exec = ("ExecStart=/usr/local/libexec/vdi-usb-monitor serve "
"--any-storage --listen 127.0.0.1:40001")
else:
service_exec = (f"ExecStart=/usr/local/libexec/vdi-usb-monitor serve --vendor {args.vendor} "
f"--product {args.product} --serial {args.serial} --listen 127.0.0.1:40001")
service_text = re.sub(r"^ExecStart=.*$", service_exec, service_text, flags=re.MULTILINE)
service_fd, service_path = tempfile.mkstemp(prefix="vdi-usb-monitor-", suffix=".service")
os.close(service_fd)
service_tmp = Path(service_path)
service_tmp.write_text(service_text)
try:
subprocess.run(["scp", "-q", str(service_tmp),
f"{args.box}:{stage}/vdi-usb-monitor.service"], check=True)
finally:
service_tmp.unlink(missing_ok=True)
if args.any_storage:
env = 'VDI_USB_MODE=any-storage\n'
rule = ('# VDI USB: ignore USB disks locally; the monitor checks exclusive use\n'
'SUBSYSTEM=="block", ENV{ID_BUS}=="usb", ENV{ID_TYPE}=="disk", '
'ENV{UDISKS_IGNORE}="1"\n')
else:
env = f'VDI_USB_VENDOR={args.vendor}\nVDI_USB_PRODUCT={args.product}\nVDI_USB_SERIAL={args.serial}\n'
rule = (f'# VDI USB device: only the approved device\nSUBSYSTEM=="block", '
f'ATTRS{{idVendor}}=="{args.vendor}", ATTRS{{idProduct}}=="{args.product}", '
f'ATTRS{{serial}}=="{args.serial}", ENV{{UDISKS_IGNORE}}="1"\n')
box_install = '''import pathlib,shutil,subprocess,sys
stage,backup,env,rule=sys.argv[1:]
backup=pathlib.Path(backup)
@@ -126,18 +156,36 @@ NoNewPrivileges=yes
PrivateTmp=yes
[Install]
WantedBy=multi-user.target
'''
qmp_args = ("--any-storage" if args.any_storage else
f"--vendor {args.vendor} --product {args.product}")
qmp_unit = f'''[Unit]
Description=VDI USB QMP endpoint for VM {args.vm}
After=network-online.target vdi-usb-tunnel-{args.vm}.service
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/local/libexec/vdi-usb-device-qmp.py watch --vm {args.vm} --port 40001 --bus ehci-2.0 {qmp_args}
Restart=always
RestartSec=3
NoNewPrivileges=yes
PrivateTmp=yes
[Install]
WantedBy=multi-user.target
'''
sftp = client.open_sftp()
try:
for path, content in [(f"{host_dir}/known_hosts", known),
(f"/etc/systemd/system/vdi-usb-tunnel-{args.vm}.service", unit),
(f"/etc/systemd/system/vdi-usb-qmp-{args.vm}.service", qmp_unit),
("/usr/local/libexec/vdi-usb-device-qmp.py", (repo / "tools/usb-device-qmp.py").read_text())]:
with sftp.open(path, "w") as f:
f.write(content)
sftp.chmod(path, 0o600 if "known_hosts" in path else 0o644)
mode = 0o600 if "known_hosts" in path else (0o755 if path.endswith("usb-device-qmp.py") else 0o644)
sftp.chmod(path, mode)
finally:
sftp.close()
pve_run(client, f"systemctl daemon-reload && systemctl enable --now vdi-usb-tunnel-{args.vm}.service")
pve_run(client, f"systemctl daemon-reload && systemctl enable --now vdi-usb-tunnel-{args.vm}.service vdi-usb-qmp-{args.vm}.service")
print(json.dumps({"box_backup": backup, "pve_directory": host_dir,
"state": "prepared; unmount USB safely before starting export"}, indent=2))
finally:
@@ -149,7 +197,9 @@ if __name__ == "__main__":
parser.add_argument("--pve", required=True)
parser.add_argument("--box", required=True)
parser.add_argument("--vm", type=int, required=True)
parser.add_argument("--vendor", required=True)
parser.add_argument("--product", required=True)
parser.add_argument("--serial", required=True)
parser.add_argument("--any-storage", action="store_true",
help="accept any pure USB Mass Storage device")
parser.add_argument("--vendor")
parser.add_argument("--product")
parser.add_argument("--serial")
install(parser.parse_args())
+60
View File
@@ -0,0 +1,60 @@
param(
[ValidateSet('Apply','Restore')][string]$Action = 'Apply',
[string]$BackupDirectory = 'C:\ProgramData\VDI\usb-experience-20261104'
)
$ErrorActionPreference = 'Stop'
$user = (Get-CimInstance Win32_ComputerSystem).UserName
if (-not $user) { throw 'No signed-in desktop user; refusing to change SYSTEM AutoPlay preferences' }
$account = New-Object System.Security.Principal.NTAccount($user)
$sid = $account.Translate([System.Security.Principal.SecurityIdentifier]).Value
$base = "Registry::HKEY_USERS\$sid\Software\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers"
if (-not (Test-Path "Registry::HKEY_USERS\$sid")) { throw 'Desktop user registry is not loaded' }
$backup = Join-Path $BackupDirectory 'preferences.clixml'
$paths = @(
@{Path=$base; Name='DisableAutoplay'; Value=0; Kind='DWord'},
@{Path="$base\UserChosenExecuteHandlers\StorageOnArrival"; Name=''; Value='MSPromptEachTime'; Kind='String'},
@{Path="$base\EventHandlersDefaultSelection\StorageOnArrival"; Name=''; Value='MSPromptEachTime'; Kind='String'}
)
if ($Action -eq 'Apply') {
if (-not (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers\Handlers\MSPromptEachTime')) {
throw 'Windows Ask every time handler is unavailable'
}
New-Item -ItemType Directory -Force -Path $BackupDirectory | Out-Null
if (-not (Test-Path -LiteralPath $backup)) {
$before = foreach ($item in $paths) {
$key = Get-Item -LiteralPath $item.Path -ErrorAction SilentlyContinue
$exists = $key -and ($key.GetValueNames() -contains $item.Name)
[pscustomobject]@{Path=$item.Path; Name=$item.Name; Exists=[bool]$exists;
Value=$(if($exists){$key.GetValue($item.Name)}else{$null});
Kind=$(if($exists){$key.GetValueKind($item.Name).ToString()}else{$null})}
}
[pscustomobject]@{User=$user; Sid=$sid; Values=@($before)} | Export-Clixml -LiteralPath $backup
}
$saved = Import-Clixml -LiteralPath $backup
if ($saved.Sid -ne $sid) { throw 'Backup belongs to a different desktop user' }
foreach ($item in $paths) {
if (-not (Test-Path -LiteralPath $item.Path)) { New-Item -Path $item.Path -Force | Out-Null }
$key = [Microsoft.Win32.Registry]::Users.OpenSubKey($item.Path.Substring('Registry::HKEY_USERS\'.Length), $true)
try {
$key.SetValue($item.Name, $item.Value, [Microsoft.Win32.RegistryValueKind]$item.Kind)
if ($key.GetValue($item.Name) -ne $item.Value) { throw "Readback failed: $($item.Path)" }
} finally { $key.Close() }
}
} else {
$saved = Import-Clixml -LiteralPath $backup
if ($saved.Sid -ne $sid) { throw 'Backup belongs to a different desktop user' }
foreach ($item in $saved.Values) {
if ($item.Exists) {
if (-not (Test-Path -LiteralPath $item.Path)) { New-Item -Path $item.Path -Force | Out-Null }
$key = [Microsoft.Win32.Registry]::Users.OpenSubKey($item.Path.Substring('Registry::HKEY_USERS\'.Length), $true)
try { $key.SetValue($item.Name, $item.Value, [Microsoft.Win32.RegistryValueKind]$item.Kind) }
finally { $key.Close() }
} elseif (Test-Path -LiteralPath $item.Path) {
$key = [Microsoft.Win32.Registry]::Users.OpenSubKey($item.Path.Substring('Registry::HKEY_USERS\'.Length), $true)
try { $key.DeleteValue($item.Name, $false) } finally { $key.Close() }
}
}
}
[pscustomobject]@{Action=$Action; User=$user; Sid=$sid; Backup=$backup;
StorageOnArrival=(Get-Item -LiteralPath "$base\UserChosenExecuteHandlers\StorageOnArrival").GetValue('');
DisableAutoplay=(Get-Item -LiteralPath $base).GetValue('DisableAutoplay')} | ConvertTo-Json -Compress
+6
View File
@@ -33,6 +33,12 @@ class UsbQmpTests(unittest.TestCase):
device = next(a for n, a in q.calls if n == "device_add")
self.assertEqual(device["filter"], "0x08:0x0951:0x1666:-1:1|-1:-1:-1:-1:0")
def test_any_storage_filter_keeps_hid_and_hub_out(self):
q = FakeQmp()
usb.attach(q, 100, 40001, "ehci-2.0")
device = next(a for n, a in q.calls if n == "device_add")
self.assertEqual(device["filter"], "0x08:-1:-1:-1:1|-1:-1:-1:-1:0")
def test_busy_endpoint_is_never_replaced(self):
q = FakeQmp(occupied=True)
with self.assertRaisesRegex(RuntimeError, "already exists"):
+49 -7
View File
@@ -54,7 +54,14 @@ def peripherals(qmp):
return {x["name"] for x in qmp.call("qom-list", {"path": "/machine/peripheral"})}
def attach(qmp, vm, port, bus, vendor, product):
def storage_filter(vendor=None, product=None):
"""Allow only USB Mass Storage, optionally narrowed to one VID/PID."""
if vendor is None or product is None:
return "0x08:-1:-1:-1:1|-1:-1:-1:-1:0"
return f"0x08:0x{vendor}:0x{product}:-1:1|-1:-1:-1:-1:0"
def attach(qmp, vm, port, bus, vendor=None, product=None):
channel, device = ids(vm)
channels = {x["label"]: x for x in qmp.call("query-chardev")}
if channel in channels or device in peripherals(qmp):
@@ -70,7 +77,7 @@ def attach(qmp, vm, port, bus, vendor, product):
qmp.call("device_add", {
"driver": "usb-redir", "id": device, "chardev": channel, "bus": bus,
# QEMU uses ':' within rules; spice-client uses ',' instead.
"filter": f"0x08:0x{vendor}:0x{product}:-1:1|-1:-1:-1:-1:0",
"filter": storage_filter(vendor, product),
})
except Exception:
# Roll back only the channel created by this invocation.
@@ -102,28 +109,63 @@ def status(qmp, vm):
}
def ensure(qmp, vm, port, bus, vendor=None, product=None):
"""Attach the runtime endpoint if the VM is running and it is absent."""
channel, device = ids(vm)
if device not in peripherals(qmp):
attach(qmp, vm, port, bus, vendor, product)
def watch(vm, port, bus, vendor=None, product=None, interval=3):
"""Keep the runtime endpoint attached across VM restarts."""
while True:
try:
qmp = Qmp(vm)
try:
ensure(qmp, vm, port, bus, vendor, product)
finally:
qmp.close()
except (OSError, RuntimeError) as exc:
print(f"waiting for VM/QMP: {exc}", flush=True)
time.sleep(interval)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["status", "attach", "detach"])
parser.add_argument("action", choices=["status", "attach", "detach", "watch"])
parser.add_argument("--vm", type=int, required=True)
parser.add_argument("--port", type=int, default=40001)
parser.add_argument("--bus", default="ehci-2.0")
parser.add_argument("--vendor")
parser.add_argument("--product")
parser.add_argument("--any-storage", action="store_true",
help="Allow any pure USB Mass Storage device")
parser.add_argument("--guest-ejected", action="store_true",
help="Confirm the guest has safely ejected the USB device before detach")
args = parser.parse_args()
if args.vm < 100 or not 1 <= args.port <= 65535:
parser.error("invalid VM ID or local tunnel port")
if args.action == "attach" and not all(
re.fullmatch(r"[0-9a-fA-F]{4}", x or "") for x in [args.vendor, args.product]):
parser.error("attach requires an exact four-digit --vendor and --product")
if args.action in ("attach", "watch"):
exact = all(re.fullmatch(r"[0-9a-fA-F]{4}", x or "") for x in [args.vendor, args.product])
if args.any_storage and (args.vendor or args.product):
parser.error("--any-storage cannot be combined with --vendor/--product")
if not args.any_storage and not exact:
parser.error("attach/watch requires --any-storage or exact --vendor and --product")
elif args.any_storage or args.vendor or args.product:
parser.error("--vendor/--product/--any-storage are only valid for attach/watch")
if args.action == "watch":
watch(args.vm, args.port, args.bus,
None if args.any_storage else args.vendor.lower(),
None if args.any_storage else args.product.lower())
return
if args.action == "detach" and not args.guest_ejected:
parser.error("safely eject in the guest first, then pass --guest-ejected")
qmp = Qmp(args.vm)
try:
if args.action == "attach":
attach(qmp, args.vm, args.port, args.bus, args.vendor.lower(), args.product.lower())
attach(qmp, args.vm, args.port, args.bus,
None if args.any_storage else args.vendor.lower(),
None if args.any_storage else args.product.lower())
elif args.action == "detach":
detach(qmp, args.vm)
print(json.dumps(status(qmp, args.vm), ensure_ascii=False, indent=2))