功能:扩展U盘兼容并优化插拔响应和导出负载
This commit is contained in:
parent
b2de05c6a6
commit
bb5f554820
86
docs/usb-any-storage-20261104.md
Normal file
86
docs/usb-any-storage-20261104.md
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
# 任意 U 盘透传实现(2026-11-04)
|
||||||
|
|
||||||
|
在已验证的真实 USB 透传链路上,将盒子端策略从固定 VID/PID/序列号扩展为
|
||||||
|
“任意纯 USB Mass Storage 设备”。键盘、鼠标、Hub 和显示设备仍由盒子本地使用。
|
||||||
|
|
||||||
|
## 行为
|
||||||
|
|
||||||
|
- 一个盒子、一个 VM 同时只导出一个存储设备;多个 U 盘同时插入时按盒子扫描顺序使用,
|
||||||
|
当前设备拔出后再接入下一个。
|
||||||
|
- 设备必须是纯存储设备,所有 USB interface class 都必须为 `08`;键鼠、Hub 和复合设备拒绝。
|
||||||
|
- 盒子检查分区是否本地挂载、是否有 holder 或作为 swap;发现本地占用时等待,不强制卸载。
|
||||||
|
- QEMU 使用 `0x08:-1:-1:-1:1` 过滤器,允许任意 USB Mass Storage,仍拒绝其他 USB 类别。
|
||||||
|
- PVE QMP watcher 在 VM/PVE 重启后重新建立运行时 `usb-redir` 设备。
|
||||||
|
|
||||||
|
## 部署入口
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python tools/deploy-usb-device-poc.py \
|
||||||
|
--pve PVE_HOST --box armbian@BOX_HOST --vm 100 --any-storage
|
||||||
|
```
|
||||||
|
|
||||||
|
部署前应在 Windows 中安全弹出当前 U 盘。部署器会安装盒子监控服务、USB 隧道和
|
||||||
|
`vdi-usb-qmp-100.service`;不会修改 VM 固定配置、GPU、显示或键鼠输入链路。
|
||||||
|
|
||||||
|
旧的精确设备策略仍可用:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python tools/deploy-usb-device-poc.py \
|
||||||
|
--pve PVE_HOST --box armbian@BOX_HOST --vm 100 \
|
||||||
|
--vendor 0951 --product 1666 --serial SERIAL
|
||||||
|
```
|
||||||
|
|
||||||
|
## 验收
|
||||||
|
|
||||||
|
至少用三只不同品牌或不同 VID/PID 的 U 盘测试:插入后 Windows 出现真实
|
||||||
|
USB Mass Storage 和盘符,读写大文件后校验 SHA-256;再测试安全弹出、拔插、
|
||||||
|
两个 U 盘同时插入,以及 VM/PVE 重启后的自动恢复。当前 Rust 单元测试 10/10、
|
||||||
|
Python QMP 测试 4/4 通过。已现场验证另一只 SanDisk 0781:5591 在 Windows
|
||||||
|
识别为 USBSTOR,F: NTFS 数据分区和 G: FAT32 UQITONG_ESP 分区均 Healthy。
|
||||||
|
多盘吞吐和 VM/PVE 重启后的恢复仍待验收;QMP watcher 已实现,但尚未现场安装。
|
||||||
|
|
||||||
|
## 插入体验优化
|
||||||
|
|
||||||
|
2026-11-04 已将当前 Windows 用户 test 的 StorageOnArrival 从 MSOpenFolder
|
||||||
|
改为 MSPromptEachTime,并保留自动播放开启。双分区装机盘仍显示两个卷,
|
||||||
|
不会再按“打开文件夹”这个默认操作自动打开两个窗口;提示数量和通知外观由 Windows 决定。
|
||||||
|
|
||||||
|
脚本 `tools/set-usb-experience.ps1` 可重复 Apply,并支持 Restore;仅修改三项
|
||||||
|
自动播放首选项,使用首次运行保存的原值回退。Windows 已执行 Apply 并回读成功。
|
||||||
|
备份路径:`C:\ProgramData\VDI\usb-experience-20261104\preferences.clixml`。
|
||||||
|
|
||||||
|
盒子监控程序使用已处理的 USB udev 事件即时唤醒,替代原来的每 2 秒轮询;
|
||||||
|
500ms 兜底扫描负责启动时已有设备和事件监听不可用的情况。活动会话直接核对
|
||||||
|
已导出的 sysfs 设备身份,不再因另一个 USB 设备扫描失败而误断开。
|
||||||
|
快速插盘时须等 `bNumInterfaces` 声明的所有接口出现后才做存储类型判断,
|
||||||
|
防止接口尚未枚举完整的存储/HID 复合设备被误接入。
|
||||||
|
日志包含 `usb_time_ms`、`local_check_ms`、`since_latest_usb_event_ms`;最后一项
|
||||||
|
仅为最近事件至导出调用的时间,不代表从物理插入至 Windows 完全可用的总时间。
|
||||||
|
|
||||||
|
盒子已离线测试并编译、部署(更新时无 U 盘连接),服务 active,udevadm 子进程正常。
|
||||||
|
旧二进制备份在 `/home/armbian/vdi-terminal/backups/usb-events-20261104-110747/`。
|
||||||
|
未重启 VM、Moonlight、Sunshine、Explorer,未修改启动分区和系统原生安全删除行为。
|
||||||
|
随后实测事件至导出调用为 5~8ms(仅盒子内部时间)。
|
||||||
|
|
||||||
|
继续排查发现发行版 usbredirect 0.13.0 的连接回调无条件订阅 G_IO_OUT,
|
||||||
|
现场导出进程曾占约 96% 的一个 CPU 核心。官方 0.15.0 的 update_watch() 按
|
||||||
|
usbredirhost_has_data_to_write() 动态监听;已从官方发布包编译私有版本:
|
||||||
|
|
||||||
|
- 源码:https://www.spice-space.org/download/usbredir/usbredir-0.15.0.tar.xz
|
||||||
|
- 源码 SHA256:`6dc2a380277688a068191245dac2ab7063a552999d8ac3ad8e841c10ff050961`
|
||||||
|
- 私有程序:`/usr/local/libexec/vdi-usbredirect`
|
||||||
|
- 二进制 SHA256:`58b58b9d9ab017d3221e44f83c0794ae2977ef9e020fcb8df959eef997ae8e4a`
|
||||||
|
- 构建脚本:`tools/build-usbredirect-private.sh`;头文件仅下载并解包,没有安装或升级系统 GLib/libusb。
|
||||||
|
- 盒子配置:`/etc/vdi-usb-monitor/device.env` 新增
|
||||||
|
`VDI_USBREDIRECT_BINARY=/usr/local/libexec/vdi-usbredirect`。
|
||||||
|
- 切换前备份:`/home/armbian/vdi-terminal/backups/usb-exporter-20261104-112031/`。
|
||||||
|
|
||||||
|
运行时 CPU 实测降至约 1%。官方 filter 29 项、serializer 1 项测试全部通过;
|
||||||
|
Rust 10 项测试通过。Windows 自动播放设置已回读验证,PowerShell 语法检查通过。
|
||||||
|
用户第一次复测仍反馈菜单慢,后续保持连接并再测后明确反馈“现在已经很快了”。
|
||||||
|
已确认不再自动打开文件夹;右下角提示和弹出菜单速度通过本次用户现场验收,
|
||||||
|
但没有测量从物理插入至菜单可用的完整耗时,也不代表长时间稳定性验收完成。
|
||||||
|
|
||||||
|
回退时先在 Windows 安全弹出并物理拔下 U 盘,再停止盒子 USB 服务,
|
||||||
|
从上述备份恢复二进制和 device.env,启动服务即可。Windows 自动播放可用
|
||||||
|
`C:\ProgramData\VDI\usb-experience-20261104\set-usb-experience.ps1 -Action Restore` 回退。
|
||||||
@ -1,12 +1,13 @@
|
|||||||
# USB 设备透传 POC
|
# USB 设备透传
|
||||||
|
|
||||||
将盒子上指定的 U 盘经 usbredir + SSH + QEMU 接入 Windows,枚举真实 VID/PID/序列号和
|
将盒子上的纯 USB 存储设备经 usbredir + SSH + QEMU 接入 Windows,枚举真实
|
||||||
USBSTOR,使用 Windows 自带驱动。这是 Moonlight 显示会话之外的设备通道,不是网络文件盘。
|
VID/PID/序列号和 USBSTOR,使用 Windows 自带驱动。这是 Moonlight 显示会话之外的
|
||||||
当前只支持明确登记的一个纯 USB 存储设备、一个盒子和一个 VM;盒子不调用 Proxmox API。
|
设备通道,不是网络文件盘。默认策略允许任意一个纯 USB 存储设备;一个盒子和一个
|
||||||
|
VM 同时只导出一个设备,键盘、鼠标、Hub 和显示设备仍由盒子本地使用。
|
||||||
|
|
||||||
- `src/main.rs`:Rust 标准库实现设备扫描、精确匹配、本地挂载/占用保护、导出及拔插恢复。
|
- `src/main.rs`:Rust 标准库实现设备扫描、存储类筛选、本地挂载/占用保护、导出及拔插恢复。
|
||||||
- `etc/vdi-usb-monitor.service`:盒子服务,读取 root 管理的单设备白名单。
|
- `etc/vdi-usb-monitor.service`:盒子服务,默认使用 `--any-storage`。
|
||||||
- `../../tools/deploy-usb-device-poc.py`:管理员部署和受限 SSH 隧道。
|
- `../../tools/deploy-usb-device-poc.py`:管理员部署、受限 SSH 隧道和 QMP 自动恢复服务。
|
||||||
- `../../tools/usb-device-qmp.py`:在 PVE 节点操作独立 QMP 热插拔端点。
|
- `../../tools/usb-device-qmp.py`:在 PVE 节点操作独立 QMP 热插拔端点。
|
||||||
- `../../tools/test-usb-device-poc.ps1`:Windows USB 身份和文件回读校验。
|
- `../../tools/test-usb-device-poc.ps1`:Windows USB 身份和文件回读校验。
|
||||||
|
|
||||||
@ -17,12 +18,29 @@ cargo test --offline
|
|||||||
cargo build --release --offline
|
cargo build --release --offline
|
||||||
target/release/vdi-usb-monitor list
|
target/release/vdi-usb-monitor list
|
||||||
sudo target/release/vdi-usb-monitor serve \
|
sudo target/release/vdi-usb-monitor serve \
|
||||||
--vendor 0951 --product 1666 --serial YOUR_USB_SERIAL --listen 127.0.0.1:40001
|
--any-storage --listen 127.0.0.1:40001
|
||||||
```
|
```
|
||||||
|
|
||||||
`list` 输出 JSON。`serve` 必须指定非空序列号,只能监听 IPv4 回环地址;
|
`list` 输出 JSON。`serve --any-storage` 只接受纯 USB Mass Storage 类设备,
|
||||||
拒绝键鼠、Hub、包含非存储接口的复合设备以及本地尚在使用的磁盘。
|
只能监听 IPv4 回环地址;拒绝键鼠、Hub、包含非存储接口的复合设备以及本地尚在使用
|
||||||
|
的磁盘。仍可使用 `--vendor/--product/--serial` 保留旧的精确设备策略。
|
||||||
本地已挂载时不会强制卸载,应先关闭本地文件操作并正常卸载。
|
本地已挂载时不会强制卸载,应先关闭本地文件操作并正常卸载。
|
||||||
|
|
||||||
|
插拔检测使用 `udevadm monitor --udev --property --subsystem-match=usb` 事件,
|
||||||
|
空闲时每 500ms 扫描兜底,活动设备每秒核对当前实例;其他设备的 sysfs 扫描错误
|
||||||
|
不会再断开正在导出的 U 盘。日志记录 Unix 毫秒时间、占用检查耗时和最近 USB 事件
|
||||||
|
至启动导出的间隔;后者不包含物理枚举、网络连接或 Windows 挂载时间。
|
||||||
|
|
||||||
|
Windows 端 `tools/set-usb-experience.ps1` 支持 Apply/Restore,为当前登录用户将
|
||||||
|
存储设备自动播放设置为“每次询问”,原设置保存在 ProgramData。不会改 U 盘分区、
|
||||||
|
隐藏启动分区、关闭通知、重启 Explorer 或更改其他任务栏图标。
|
||||||
|
|
||||||
|
发行版 usbredirect 0.13 的持续 G_IO_OUT 监听可能造成 CPU 空转。盒子当前使用
|
||||||
|
官方 0.15 的私有构建,保留 `/usr/bin/usbredirect`。可使用
|
||||||
|
`tools/build-usbredirect-private.sh` 构建后,将程序安装到
|
||||||
|
`/usr/local/libexec/vdi-usbredirect`,再在 root 管理的 device.env 中配置
|
||||||
|
`VDI_USBREDIRECT_BINARY=/usr/local/libexec/vdi-usbredirect`。
|
||||||
|
未配置时监控程序仍使用 `/usr/bin/usbredirect`;更新运行程序前须安全弹出并拔下 U 盘。
|
||||||
|
|
||||||
完整现场、部署、限制和回退见
|
完整现场、部署、限制和回退见
|
||||||
[`docs/usb-device-poc-20261103.md`](../../docs/usb-device-poc-20261103.md)。
|
[`docs/usb-device-poc-20261103.md`](../../docs/usb-device-poc-20261103.md)。
|
||||||
|
|||||||
@ -1,11 +1,11 @@
|
|||||||
[Unit]
|
[Unit]
|
||||||
Description=VDI approved USB storage redirection (device POC)
|
Description=VDI USB Mass Storage redirection
|
||||||
After=network.target systemd-udevd.service
|
After=network.target systemd-udevd.service
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
Type=simple
|
Type=simple
|
||||||
EnvironmentFile=/etc/vdi-usb-monitor/device.env
|
EnvironmentFile=/etc/vdi-usb-monitor/device.env
|
||||||
ExecStart=/usr/local/libexec/vdi-usb-monitor serve --vendor ${VDI_USB_VENDOR} --product ${VDI_USB_PRODUCT} --serial ${VDI_USB_SERIAL} --listen 127.0.0.1:40001
|
ExecStart=/usr/local/libexec/vdi-usb-monitor serve --any-storage --listen 127.0.0.1:40001
|
||||||
Restart=on-failure
|
Restart=on-failure
|
||||||
RestartSec=3
|
RestartSec=3
|
||||||
KillMode=control-group
|
KillMode=control-group
|
||||||
|
|||||||
@ -1,6 +1,63 @@
|
|||||||
//! Device-level USB POC. Never calls the hypervisor API or exports HID devices.
|
//! Device-level USB redirection. Never calls the hypervisor API or exports HID devices.
|
||||||
use std::{collections::BTreeSet, env, fs, net::SocketAddr, path::{Path, PathBuf},
|
use std::{collections::BTreeSet, env, fs, io::{BufRead, BufReader}, net::SocketAddr,
|
||||||
process::{self, Command}, thread, time::Duration};
|
path::{Path, PathBuf}, process::{self, Child, Command, Stdio},
|
||||||
|
sync::mpsc::{self, Receiver}, thread, time::{Duration, Instant, SystemTime, UNIX_EPOCH}};
|
||||||
|
|
||||||
|
// udev delivers completed USB changes; the timeout also covers startup and a
|
||||||
|
// stopped event monitor. The monitor never runs a command supplied by a device.
|
||||||
|
struct UsbEvents {
|
||||||
|
child: Option<Child>,
|
||||||
|
receiver: Receiver<Instant>,
|
||||||
|
last_event: Option<Instant>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UsbEvents {
|
||||||
|
fn start() -> Self {
|
||||||
|
let (sender, receiver) = mpsc::sync_channel(64);
|
||||||
|
let child = Command::new("/usr/bin/stdbuf")
|
||||||
|
.args(["-oL", "/usr/bin/udevadm", "monitor", "--udev", "--property", "--subsystem-match=usb"])
|
||||||
|
.stdout(Stdio::piped()).stderr(Stdio::null()).spawn();
|
||||||
|
let child = match child {
|
||||||
|
Ok(mut child) => {
|
||||||
|
let stdout = child.stdout.take().unwrap();
|
||||||
|
thread::spawn(move || {
|
||||||
|
for line in BufReader::new(stdout).lines() {
|
||||||
|
match line {
|
||||||
|
Ok(line) if line.starts_with("ACTION=") => { let _ = sender.try_send(Instant::now()); }
|
||||||
|
Ok(_) => {},
|
||||||
|
Err(_) => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Some(child)
|
||||||
|
}
|
||||||
|
Err(err) => { eprintln!("USB event monitor unavailable: {err}; using fallback scan"); None }
|
||||||
|
};
|
||||||
|
Self { child, receiver, last_event: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wait(&mut self, timeout: Duration) {
|
||||||
|
match self.receiver.recv_timeout(timeout) {
|
||||||
|
Ok(event) => {
|
||||||
|
self.last_event = Some(event);
|
||||||
|
while let Ok(event) = self.receiver.try_recv() { self.last_event = Some(event); }
|
||||||
|
}
|
||||||
|
Err(mpsc::RecvTimeoutError::Disconnected) => thread::sleep(timeout),
|
||||||
|
Err(mpsc::RecvTimeoutError::Timeout) => {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for UsbEvents {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(child) = self.child.as_mut() { let _ = child.kill(); let _ = child.wait(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn log_event(message: &str) {
|
||||||
|
let ms = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_millis();
|
||||||
|
eprintln!("usb_time_ms={ms} {message}");
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
struct Device {
|
struct Device {
|
||||||
@ -38,6 +95,10 @@ fn scan(root: &Path) -> Result<Vec<Device>, String> {
|
|||||||
let mut classes: Vec<_> = entries.iter().filter(|e|
|
let mut classes: Vec<_> = entries.iter().filter(|e|
|
||||||
e.file_name().to_string_lossy().starts_with(&prefix))
|
e.file_name().to_string_lossy().starts_with(&prefix))
|
||||||
.map(|e| read(&e.path(), "bInterfaceClass")).collect();
|
.map(|e| read(&e.path(), "bInterfaceClass")).collect();
|
||||||
|
// Early hotplug events can arrive before every interface is visible.
|
||||||
|
// Do not mistake the first storage interface of a composite for a pure disk.
|
||||||
|
let expected = read(&p, "bNumInterfaces").parse::<usize>().unwrap_or(0);
|
||||||
|
if expected == 0 || classes.len() != expected { continue; }
|
||||||
classes.sort();
|
classes.sort();
|
||||||
devices.push(Device {
|
devices.push(Device {
|
||||||
path: p.canonicalize().map_err(|e| e.to_string())?,
|
path: p.canonicalize().map_err(|e| e.to_string())?,
|
||||||
@ -98,38 +159,95 @@ fn hex_id(s: &str) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct Policy { vendor: String, product: String, serial: String, listen: SocketAddr }
|
enum MatchPolicy {
|
||||||
|
AnyStorage,
|
||||||
|
Exact { vendor: String, product: String, serial: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Policy { matcher: MatchPolicy, listen: SocketAddr }
|
||||||
|
|
||||||
fn parse_policy(args: &[String]) -> Result<Policy, String> {
|
fn parse_policy(args: &[String]) -> Result<Policy, String> {
|
||||||
if args.len() != 8 { return Err("serve requires --vendor XXXX --product XXXX --serial SERIAL --listen 127.0.0.1:PORT".into()); }
|
let mut any_storage = false;
|
||||||
let mut values = std::collections::BTreeMap::new();
|
let mut vendor = None;
|
||||||
for pair in args.chunks(2) {
|
let mut product = None;
|
||||||
if !["--vendor", "--product", "--serial", "--listen"].contains(&pair[0].as_str())
|
let mut serial = None;
|
||||||
|| values.insert(pair[0].as_str(), pair[1].as_str()).is_some() {
|
let mut listen = None;
|
||||||
return Err("unknown or duplicate policy option".into());
|
let mut i = 0;
|
||||||
|
while i < args.len() {
|
||||||
|
match args[i].as_str() {
|
||||||
|
"--any-storage" => {
|
||||||
|
if any_storage { return Err("duplicate --any-storage".into()); }
|
||||||
|
any_storage = true;
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
"--vendor" | "--product" | "--serial" | "--listen" => {
|
||||||
|
if i + 1 >= args.len() { return Err("missing value for policy option".into()); }
|
||||||
|
let value = args[i + 1].clone();
|
||||||
|
let target = match args[i].as_str() {
|
||||||
|
"--vendor" => &mut vendor,
|
||||||
|
"--product" => &mut product,
|
||||||
|
"--serial" => &mut serial,
|
||||||
|
_ => &mut listen,
|
||||||
|
};
|
||||||
|
if target.replace(value).is_some() { return Err("duplicate policy option".into()); }
|
||||||
|
i += 2;
|
||||||
|
}
|
||||||
|
_ => return Err("unknown policy option".into()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let vendor = values["--vendor"].to_ascii_lowercase();
|
let listen: SocketAddr = listen.ok_or("--listen is required")?.parse()
|
||||||
let product = values["--product"].to_ascii_lowercase();
|
.map_err(|_| "invalid listen address")?;
|
||||||
let serial = values["--serial"].to_string();
|
if !listen.ip().is_loopback() || !listen.is_ipv4() || listen.port() == 0 {
|
||||||
let listen: SocketAddr = values["--listen"].parse().map_err(|_| "invalid listen address")?;
|
return Err("an IPv4 loopback listener with a nonzero port is required".into());
|
||||||
if !hex_id(&vendor) || !hex_id(&product) || serial.is_empty()
|
}
|
||||||
|| serial.chars().any(char::is_control) || !listen.ip().is_loopback()
|
let matcher = if any_storage {
|
||||||
|| !listen.is_ipv4() || listen.port() == 0 {
|
if vendor.is_some() || product.is_some() || serial.is_some() {
|
||||||
return Err("exact VID/PID/serial and an IPv4 loopback listener are required".into());
|
return Err("--any-storage cannot be combined with an exact device identity".into());
|
||||||
|
}
|
||||||
|
MatchPolicy::AnyStorage
|
||||||
|
} else {
|
||||||
|
let vendor = vendor.ok_or("exact mode requires --vendor")?.to_ascii_lowercase();
|
||||||
|
let product = product.ok_or("exact mode requires --product")?.to_ascii_lowercase();
|
||||||
|
let serial = serial.ok_or("exact mode requires --serial")?;
|
||||||
|
if !hex_id(&vendor) || !hex_id(&product) || serial.is_empty()
|
||||||
|
|| serial.chars().any(char::is_control) {
|
||||||
|
return Err("exact mode requires valid VID/PID and a nonempty serial".into());
|
||||||
|
}
|
||||||
|
MatchPolicy::Exact { vendor, product, serial }
|
||||||
|
};
|
||||||
|
Ok(Policy { matcher, listen })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn matches_policy(device: &Device, p: &Policy) -> bool {
|
||||||
|
match &p.matcher {
|
||||||
|
MatchPolicy::AnyStorage => true,
|
||||||
|
MatchPolicy::Exact { vendor, product, serial } =>
|
||||||
|
device.vendor == vendor.as_str() && device.product == product.as_str()
|
||||||
|
&& device.serial == serial.as_str(),
|
||||||
}
|
}
|
||||||
Ok(Policy { vendor, product, serial, listen })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn select<'a>(devices: &'a [Device], p: &Policy) -> Result<&'a Device, String> {
|
fn select<'a>(devices: &'a [Device], p: &Policy) -> Result<&'a Device, String> {
|
||||||
let found: Vec<_> = devices.iter().filter(|d|
|
let found: Vec<_> = devices.iter().filter(|d|
|
||||||
d.vendor == p.vendor && d.product == p.product && d.serial == p.serial).collect();
|
matches_policy(d, p) && storage_only(&d.device_class, &d.classes)
|
||||||
if found.len() != 1 { return Err(format!("waiting for exactly one approved device; found {}", found.len())); }
|
&& d.bus != 0 && d.address != 0).collect();
|
||||||
let d = found[0];
|
match &p.matcher {
|
||||||
if !storage_only(&d.device_class, &d.classes) || d.bus == 0 || d.address == 0 {
|
MatchPolicy::Exact { .. } if found.len() != 1 =>
|
||||||
return Err("not a pure USB mass-storage device; refusing export".into());
|
Err(format!("waiting for exactly one approved device; found {}", found.len())),
|
||||||
|
_ => found.into_iter().next().ok_or_else(||
|
||||||
|
"waiting for a pure USB mass-storage device".into()),
|
||||||
}
|
}
|
||||||
Ok(d)
|
}
|
||||||
|
|
||||||
|
fn still_present(device: &Device) -> bool {
|
||||||
|
// An unrelated USB device can vanish while a full sysfs scan is running.
|
||||||
|
// Inspect only the exported instance so that does not disconnect this disk.
|
||||||
|
read(&device.path, "busnum").parse::<u16>().ok() == Some(device.bus)
|
||||||
|
&& read(&device.path, "devnum").parse::<u16>().ok() == Some(device.address)
|
||||||
|
&& read(&device.path, "idVendor") == device.vendor
|
||||||
|
&& read(&device.path, "idProduct") == device.product
|
||||||
|
&& read(&device.path, "serial") == device.serial
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run() -> Result<(), String> {
|
fn run() -> Result<(), String> {
|
||||||
@ -144,40 +262,47 @@ fn run() -> Result<(), String> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
if args.first().map(String::as_str) != Some("serve") {
|
if args.first().map(String::as_str) != Some("serve") {
|
||||||
return Err("usage: vdi-usb-monitor list | serve --vendor XXXX --product XXXX --serial SERIAL --listen 127.0.0.1:PORT".into());
|
return Err("usage: vdi-usb-monitor list | serve (--any-storage | --vendor XXXX --product XXXX --serial SERIAL) --listen 127.0.0.1:PORT".into());
|
||||||
}
|
}
|
||||||
let policy = parse_policy(&args[1..])?;
|
let policy = parse_policy(&args[1..])?;
|
||||||
|
let redirect_binary = env::var("VDI_USBREDIRECT_BINARY").unwrap_or_else(|_| "/usr/bin/usbredirect".into());
|
||||||
|
if !Path::new(&redirect_binary).is_absolute() || !Path::new(&redirect_binary).is_file() {
|
||||||
|
return Err("VDI_USBREDIRECT_BINARY must name an installed absolute executable path".into());
|
||||||
|
}
|
||||||
|
log_event(&format!("USB exporter: {redirect_binary}"));
|
||||||
|
let mut events = UsbEvents::start();
|
||||||
let mut last = String::new();
|
let mut last = String::new();
|
||||||
loop {
|
loop {
|
||||||
let result: Result<(), String> = scan(Path::new("/sys/bus/usb/devices")).and_then(|devices| {
|
let result: Result<(), String> = scan(Path::new("/sys/bus/usb/devices")).and_then(|devices| {
|
||||||
let device = select(&devices, &policy)?;
|
let device = select(&devices, &policy)?;
|
||||||
|
let checked_at = Instant::now();
|
||||||
check_local_use(device)?;
|
check_local_use(device)?;
|
||||||
// Bus/address selects one physical instance, never an arbitrary VID/PID match.
|
// Bus/address selects one physical instance, never an arbitrary VID/PID match.
|
||||||
let selector = format!("{}-{}", device.bus, device.address);
|
let selector = format!("{}-{}", device.bus, device.address);
|
||||||
eprintln!("exporting approved storage {} at {}", device.bus_id, policy.listen);
|
log_event(&format!("exporting storage {} {:}:{:} at {}; local_check_ms={} since_latest_usb_event_ms={}",
|
||||||
let mut child = Command::new("/usr/bin/usbredirect")
|
device.bus_id, device.vendor, device.product, policy.listen,
|
||||||
|
checked_at.elapsed().as_millis(),
|
||||||
|
events.last_event.map(|time| time.elapsed().as_millis().to_string()).unwrap_or_else(|| "startup".into())));
|
||||||
|
let mut child = Command::new(&redirect_binary)
|
||||||
.args(["--device", &selector, "--as", &policy.listen.to_string(), "--keepalive"])
|
.args(["--device", &selector, "--as", &policy.listen.to_string(), "--keepalive"])
|
||||||
.spawn().map_err(|e| e.to_string())?;
|
.spawn().map_err(|e| e.to_string())?;
|
||||||
loop {
|
loop {
|
||||||
if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
|
if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
|
||||||
return Err(format!("export session ended: {status}; waiting before retry"));
|
return Err(format!("export session ended: {status}; waiting before retry"));
|
||||||
}
|
}
|
||||||
thread::sleep(Duration::from_secs(1));
|
events.wait(Duration::from_secs(1));
|
||||||
let present = scan(Path::new("/sys/bus/usb/devices")).ok().map(|current| {
|
if !still_present(device) {
|
||||||
select(¤t, &policy).map(|d| d.bus == device.bus
|
|
||||||
&& d.address == device.address && d.bus_id == device.bus_id).unwrap_or(false)
|
|
||||||
}).unwrap_or(false);
|
|
||||||
if !present {
|
|
||||||
let _ = child.kill();
|
let _ = child.kill();
|
||||||
let _ = child.wait();
|
let _ = child.wait();
|
||||||
|
log_event(&format!("storage {} disconnected", device.bus_id));
|
||||||
return Err("approved USB device disconnected; waiting for reinsertion".into());
|
return Err("approved USB device disconnected; waiting for reinsertion".into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
if let Err(message) = result {
|
if let Err(message) = result {
|
||||||
if message != last { eprintln!("{message}"); last = message; }
|
if message != last { log_event(&message); last = message; }
|
||||||
}
|
}
|
||||||
thread::sleep(Duration::from_secs(2));
|
events.wait(Duration::from_millis(500));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -206,6 +331,14 @@ mod tests {
|
|||||||
assert!(parse_policy(&policy(address)).is_err());
|
assert!(parse_policy(&policy(address)).is_err());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn any_storage_policy_accepts_loopback_listener() {
|
||||||
|
let p = parse_policy(&["--any-storage".into(), "--listen".into(), "127.0.0.1:40001".into()]).unwrap();
|
||||||
|
assert!(matches!(p.matcher, MatchPolicy::AnyStorage));
|
||||||
|
assert!(parse_policy(&["--any-storage".into(), "--vendor".into(), "0951".into(),
|
||||||
|
"--listen".into(), "127.0.0.1:40001".into()]).is_err());
|
||||||
|
}
|
||||||
#[test]
|
#[test]
|
||||||
fn mounted_partition_blocks_parent_disk_export() {
|
fn mounted_partition_blocks_parent_disk_export() {
|
||||||
let numbers = BTreeSet::from(["8:0".into(), "8:1".into()]);
|
let numbers = BTreeSet::from(["8:0".into(), "8:1".into()]);
|
||||||
@ -226,6 +359,67 @@ mod tests {
|
|||||||
assert!(select(&[d.clone()], &p).is_ok());
|
assert!(select(&[d.clone()], &p).is_ok());
|
||||||
assert!(select(&[d.clone(), d], &p).is_err());
|
assert!(select(&[d.clone(), d], &p).is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn any_storage_selects_storage_and_rejects_hid() {
|
||||||
|
let p = parse_policy(&["--any-storage".into(), "--listen".into(), "127.0.0.1:40001".into()]).unwrap();
|
||||||
|
let storage = Device {
|
||||||
|
path: PathBuf::from("/sys/test"), bus_id: "3-1".into(),
|
||||||
|
vendor: "1234".into(), product: "5678".into(), serial: "".into(),
|
||||||
|
name: "storage".into(), bus: 3, address: 5,
|
||||||
|
classes: vec!["08".into()], device_class: "00".into(),
|
||||||
|
};
|
||||||
|
let hid = Device { classes: vec!["03".into()], ..storage.clone() };
|
||||||
|
assert_eq!(select(&[hid, storage.clone()], &p).unwrap().bus_id, "3-1");
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn usb_events_wake_and_coalesce_without_waiting_for_the_scan_timer() {
|
||||||
|
let (sender, receiver) = mpsc::sync_channel(8);
|
||||||
|
let first = Instant::now();
|
||||||
|
let latest = Instant::now();
|
||||||
|
sender.send(first).unwrap();
|
||||||
|
sender.send(latest).unwrap();
|
||||||
|
let mut events = UsbEvents { child: None, receiver, last_event: None };
|
||||||
|
events.wait(Duration::from_secs(30));
|
||||||
|
assert_eq!(events.last_event, Some(latest));
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn active_presence_check_rejects_a_replacement_on_the_same_port() {
|
||||||
|
let root = env::temp_dir().join(format!("vdi-usb-presence-{}-{}", process::id(),
|
||||||
|
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos()));
|
||||||
|
fs::create_dir(&root).unwrap();
|
||||||
|
for (name, value) in [("busnum", "3"), ("devnum", "5"), ("idVendor", "1234"),
|
||||||
|
("idProduct", "5678"), ("serial", "TEST")] {
|
||||||
|
fs::write(root.join(name), value).unwrap();
|
||||||
|
}
|
||||||
|
let device = Device { path: root.clone(), bus_id: "3-1".into(), vendor: "1234".into(),
|
||||||
|
product: "5678".into(), serial: "TEST".into(), name: "test".into(),
|
||||||
|
bus: 3, address: 5, classes: vec!["08".into()], device_class: "00".into() };
|
||||||
|
assert!(still_present(&device));
|
||||||
|
fs::write(root.join("devnum"), "6").unwrap();
|
||||||
|
assert!(!still_present(&device));
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn incomplete_composite_cannot_be_exported_as_storage() {
|
||||||
|
let root = env::temp_dir().join(format!("vdi-usb-enumeration-{}-{}", process::id(),
|
||||||
|
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos()));
|
||||||
|
let device = root.join("3-1");
|
||||||
|
fs::create_dir_all(&device).unwrap();
|
||||||
|
for (name, value) in [("idVendor", "1234"), ("idProduct", "5678"),
|
||||||
|
("bDeviceClass", "00"), ("bNumInterfaces", "2")] {
|
||||||
|
fs::write(device.join(name), value).unwrap();
|
||||||
|
}
|
||||||
|
fs::create_dir(root.join("3-1:1.0")).unwrap();
|
||||||
|
fs::write(root.join("3-1:1.0/bInterfaceClass"), "08").unwrap();
|
||||||
|
assert!(scan(&root).unwrap().is_empty());
|
||||||
|
fs::create_dir(root.join("3-1:1.1")).unwrap();
|
||||||
|
fs::write(root.join("3-1:1.1/bInterfaceClass"), "03").unwrap();
|
||||||
|
let devices = scan(&root).unwrap();
|
||||||
|
assert_eq!(devices.len(), 1);
|
||||||
|
assert!(!storage_only(&devices[0].device_class, &devices[0].classes));
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
#[test]
|
#[test]
|
||||||
fn enumeration_json_escapes_control_characters() {
|
fn enumeration_json_escapes_control_characters() {
|
||||||
assert_eq!(json_string("a\n\"\\"), "\"a\\u000a\\\"\\\\\"");
|
assert_eq!(json_string("a\n\"\\"), "\"a\\u000a\\\"\\\\\"");
|
||||||
|
|||||||
60
tools/build-usbredirect-private.sh
Normal file
60
tools/build-usbredirect-private.sh
Normal 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
|
||||||
@ -1,10 +1,12 @@
|
|||||||
#!/usr/bin/env python3
|
#!/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.
|
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).
|
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
|
Use --any-storage to accept any pure USB Mass Storage device, or provide an
|
||||||
box service, then run usb-device-qmp.py attach on the PVE node.
|
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 argparse
|
||||||
import json
|
import json
|
||||||
@ -13,6 +15,7 @@ from pathlib import Path
|
|||||||
import re
|
import re
|
||||||
import shlex
|
import shlex
|
||||||
import subprocess
|
import subprocess
|
||||||
|
import tempfile
|
||||||
import time
|
import time
|
||||||
|
|
||||||
|
|
||||||
@ -35,10 +38,16 @@ def pve_run(client, command):
|
|||||||
|
|
||||||
def install(args, password=None):
|
def install(args, password=None):
|
||||||
import paramiko
|
import paramiko
|
||||||
if not re.fullmatch(r"[0-9a-f]{4}", args.vendor) or not re.fullmatch(r"[0-9a-f]{4}", args.product):
|
exact = all(getattr(args, name, None) for name in ("vendor", "product", "serial"))
|
||||||
raise ValueError("VID/PID must be four lowercase hex digits")
|
if args.any_storage and exact:
|
||||||
if not re.fullmatch(r"[A-Za-z0-9_.-]+", args.serial) or not args.serial:
|
raise ValueError("--any-storage cannot be combined with an exact device identity")
|
||||||
raise ValueError("POC installer supports nonempty alphanumeric serials only")
|
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):
|
if not re.fullmatch(r"[a-z_][a-z0-9_-]*@[A-Za-z0-9.-]+", args.box):
|
||||||
raise ValueError("invalid box SSH destination")
|
raise ValueError("invalid box SSH destination")
|
||||||
if args.vm < 100:
|
if args.vm < 100:
|
||||||
@ -80,12 +89,33 @@ p.chmod(0o600)
|
|||||||
f'command="/bin/false" {pubkey}')
|
f'command="/bin/false" {pubkey}')
|
||||||
box_run(args.box, f"python3 - {shlex.quote(backup)} {shlex.quote(auth_line)}", auth_script)
|
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()
|
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"),
|
service_text = (repo / "terminal/usb-monitor/etc/vdi-usb-monitor.service").read_text()
|
||||||
f"{args.box}:{stage}/vdi-usb-monitor.service"], check=True)
|
if args.any_storage:
|
||||||
env = f'VDI_USB_VENDOR={args.vendor}\nVDI_USB_PRODUCT={args.product}\nVDI_USB_SERIAL={args.serial}\n'
|
service_exec = ("ExecStart=/usr/local/libexec/vdi-usb-monitor serve "
|
||||||
rule = (f'# VDI USB device POC: only the approved device\nSUBSYSTEM=="block", '
|
"--any-storage --listen 127.0.0.1:40001")
|
||||||
f'ATTRS{{idVendor}}=="{args.vendor}", ATTRS{{idProduct}}=="{args.product}", '
|
else:
|
||||||
f'ATTRS{{serial}}=="{args.serial}", ENV{{UDISKS_IGNORE}}="1"\n')
|
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
|
box_install = '''import pathlib,shutil,subprocess,sys
|
||||||
stage,backup,env,rule=sys.argv[1:]
|
stage,backup,env,rule=sys.argv[1:]
|
||||||
backup=pathlib.Path(backup)
|
backup=pathlib.Path(backup)
|
||||||
@ -126,18 +156,36 @@ NoNewPrivileges=yes
|
|||||||
PrivateTmp=yes
|
PrivateTmp=yes
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=multi-user.target
|
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()
|
sftp = client.open_sftp()
|
||||||
try:
|
try:
|
||||||
for path, content in [(f"{host_dir}/known_hosts", known),
|
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-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())]:
|
("/usr/local/libexec/vdi-usb-device-qmp.py", (repo / "tools/usb-device-qmp.py").read_text())]:
|
||||||
with sftp.open(path, "w") as f:
|
with sftp.open(path, "w") as f:
|
||||||
f.write(content)
|
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:
|
finally:
|
||||||
sftp.close()
|
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,
|
print(json.dumps({"box_backup": backup, "pve_directory": host_dir,
|
||||||
"state": "prepared; unmount USB safely before starting export"}, indent=2))
|
"state": "prepared; unmount USB safely before starting export"}, indent=2))
|
||||||
finally:
|
finally:
|
||||||
@ -149,7 +197,9 @@ if __name__ == "__main__":
|
|||||||
parser.add_argument("--pve", required=True)
|
parser.add_argument("--pve", required=True)
|
||||||
parser.add_argument("--box", required=True)
|
parser.add_argument("--box", required=True)
|
||||||
parser.add_argument("--vm", type=int, required=True)
|
parser.add_argument("--vm", type=int, required=True)
|
||||||
parser.add_argument("--vendor", required=True)
|
parser.add_argument("--any-storage", action="store_true",
|
||||||
parser.add_argument("--product", required=True)
|
help="accept any pure USB Mass Storage device")
|
||||||
parser.add_argument("--serial", required=True)
|
parser.add_argument("--vendor")
|
||||||
|
parser.add_argument("--product")
|
||||||
|
parser.add_argument("--serial")
|
||||||
install(parser.parse_args())
|
install(parser.parse_args())
|
||||||
|
|||||||
60
tools/set-usb-experience.ps1
Normal file
60
tools/set-usb-experience.ps1
Normal 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
|
||||||
@ -33,6 +33,12 @@ class UsbQmpTests(unittest.TestCase):
|
|||||||
device = next(a for n, a in q.calls if n == "device_add")
|
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")
|
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):
|
def test_busy_endpoint_is_never_replaced(self):
|
||||||
q = FakeQmp(occupied=True)
|
q = FakeQmp(occupied=True)
|
||||||
with self.assertRaisesRegex(RuntimeError, "already exists"):
|
with self.assertRaisesRegex(RuntimeError, "already exists"):
|
||||||
|
|||||||
@ -54,7 +54,14 @@ def peripherals(qmp):
|
|||||||
return {x["name"] for x in qmp.call("qom-list", {"path": "/machine/peripheral"})}
|
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)
|
channel, device = ids(vm)
|
||||||
channels = {x["label"]: x for x in qmp.call("query-chardev")}
|
channels = {x["label"]: x for x in qmp.call("query-chardev")}
|
||||||
if channel in channels or device in peripherals(qmp):
|
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", {
|
qmp.call("device_add", {
|
||||||
"driver": "usb-redir", "id": device, "chardev": channel, "bus": bus,
|
"driver": "usb-redir", "id": device, "chardev": channel, "bus": bus,
|
||||||
# QEMU uses ':' within rules; spice-client uses ',' instead.
|
# 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:
|
except Exception:
|
||||||
# Roll back only the channel created by this invocation.
|
# 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():
|
def main():
|
||||||
parser = argparse.ArgumentParser(description=__doc__)
|
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("--vm", type=int, required=True)
|
||||||
parser.add_argument("--port", type=int, default=40001)
|
parser.add_argument("--port", type=int, default=40001)
|
||||||
parser.add_argument("--bus", default="ehci-2.0")
|
parser.add_argument("--bus", default="ehci-2.0")
|
||||||
parser.add_argument("--vendor")
|
parser.add_argument("--vendor")
|
||||||
parser.add_argument("--product")
|
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",
|
parser.add_argument("--guest-ejected", action="store_true",
|
||||||
help="Confirm the guest has safely ejected the USB device before detach")
|
help="Confirm the guest has safely ejected the USB device before detach")
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
if args.vm < 100 or not 1 <= args.port <= 65535:
|
if args.vm < 100 or not 1 <= args.port <= 65535:
|
||||||
parser.error("invalid VM ID or local tunnel port")
|
parser.error("invalid VM ID or local tunnel port")
|
||||||
if args.action == "attach" and not all(
|
if args.action in ("attach", "watch"):
|
||||||
re.fullmatch(r"[0-9a-fA-F]{4}", x or "") for x in [args.vendor, args.product]):
|
exact = 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.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:
|
if args.action == "detach" and not args.guest_ejected:
|
||||||
parser.error("safely eject in the guest first, then pass --guest-ejected")
|
parser.error("safely eject in the guest first, then pass --guest-ejected")
|
||||||
qmp = Qmp(args.vm)
|
qmp = Qmp(args.vm)
|
||||||
try:
|
try:
|
||||||
if args.action == "attach":
|
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":
|
elif args.action == "detach":
|
||||||
detach(qmp, args.vm)
|
detach(qmp, args.vm)
|
||||||
print(json.dumps(status(qmp, args.vm), ensure_ascii=False, indent=2))
|
print(json.dumps(status(qmp, args.vm), ensure_ascii=False, indent=2))
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user