feat: add optional Windows virtual USB ADB device

This commit is contained in:
tongtong committed 2026-11-12 17:34:23 +08:00
1 parent 2abfb63da9
commit 08d60de364
23 files changed
+802 -26

No files matched your search

+6 -5
View File
@@ -14,6 +14,7 @@
| 目录 | 作用 | 主要语言/格式 |
| --- | --- | --- |
| `agent/` | 远程设备守护程序 ads-agent,注册设备、连接手机 ADB、建立转发并重连;源码在 `src/` | Rust、TOML |
| `usb/` | 可选 ads-usb 本机虚拟 ADB USB 设备,提供回环 USB/IP、描述符和 ADB 帧适配;Windows 使用已签名 USBip 虚拟控制器 | Rust、TOML |
| `client/` | 本地守护程序 ads-client,维护设备租约、监听本地端口并自动调用 adb connect;源码在 `src/` | Rust、TOML |
| `server/` | ads-server 控制中心、旧协议兼容转发及独立 ads-relay 中继节点 | Go |
| `server/cmd/ads-relay/` | 独立中继入口,提供短期票据认证、WSS 数据配对及可选 STUN | Go |
@@ -41,9 +42,9 @@
桌面项目下的 `bin/`、`obj/` 同样是 .NET 生成的构建产物与中间文件,已被 Git 忽略。根目录的 `adb_bridge.py` 与 `start-bridge.ps1` 是旧局域网桥接入口,分别使用 Python 和 PowerShell,不属于上述目录。
## 可选 USB 模拟功能(方案记录,尚未实现)
## 可选 USB 模拟功能(Windows 已开始实现)
用户要求:将跨平台 USB 模拟的可行性与产品设计记录在此,当前不进行实现。以下内容是后续开发的设计依据,不代表现有产品已经支持。未经用户后续要求,不因本文件而启动驱动、桥接或 UI 开发。
用户于 2026-11-12 授权新增可选 USB 模拟,先实现 Windows。当前采用独立 Rust USB/IP 虚拟 ADB 设备 + 已签名的 USBip UDE 控制器,复用现有网络隧道,包含桌面开关、驱动检测和安装脚本;详见 docs/windows-usb.md。Linux/macOS 仍仅记录方案,未经后续要求不实现其后端。以下跨平台内容保留为设计依据。
### 目标与范围
@@ -84,7 +85,7 @@
| 平台 | 候选路线 | 成本与限制 |
| --- | --- | --- |
| Windows | 使用 UDE 模拟 USB 控制器/ADB USB 设备,并连接本机桥接服务 | 需要内核驱动开发、驱动签名、管理员安装、ADB 接口绑定和兼容性验证 |
| Windows | 使用已签名 USBip UDE 控制器 + 本项目虚拟 ADB USB/IP 设备 | 已实现并验证 USB 枚举与远程 shell;安装控制器需管理员权限,不自行编写内核驱动 |
| Linux | 使用 USB/IP 的 `vhci_hcd`,配合模拟 ADB USB 设备的服务 | 需要内核模块支持、权限配置、USB/IP 请求适配及发行版兼容性验证 |
| macOS | 使用 `IOUSBHostControllerInterface` 实现虚拟 USB 控制器 | 需要向 Apple 申请 `com.apple.developer.usb.host-controller-interface` 受管理 entitlement;获批与实际验证前不承诺正式支持 |
@@ -96,14 +97,14 @@ macOS 是正式交付的最大不确定性。不能把存在 API 或实验原型
- MTP 文件传输、fastboot 以及其他 USB 功能不自动获得支持,需要独立设计与实现。
- 不将该方案描述为整台手机所有 USB 功能的透明透传。
### 后续分阶段验证(尚未启动)
### 原跨平台分阶段方案(Windows 验证进度见 docs/windows-usb.md)
1. 检查现有转发协议层、设备端接入方式,以及可复用的隧道和设备生命周期管理能力。
2. 优先完成 Windows、Linux 的最小原型验证,确认原版 ADB 能发现模拟设备并建立 USB transport。
3. 同期为 macOS 申请必要 entitlement 并验证原型;权限和兼容性验证通过后,再列为正式支持。
4. 验证 ADB 命令、USB 筛选、目标第三方软件、多设备、断线重连及组件安装/卸载行为,再决定正式产品范围。
当前仅记录设计,不修改运行逻辑,不添加驱动或安装组件,不启动上述验证工作。
当前 Windows 实现以 docs/windows-usb.md 的范围及验证记录为准;其余平台仍仅记录设计。
### 参考资料
Generated
+11
View File
@@ -43,6 +43,17 @@ dependencies = [
"webrtc",
]
[[package]]
name = "ads-usb"
version = "0.1.0"
dependencies = [
"anyhow",
"clap",
"tokio",
"tracing",
"tracing-subscriber",
]
[[package]]
name = "aead"
version = "0.5.2"
+1 -1
View File
@@ -1,5 +1,5 @@
[workspace]
members = ["crates/ads-core", "agent", "client"]
members = ["crates/ads-core", "agent", "client", "usb"]
resolver = "2"
[workspace.package]
+5 -2
View File
@@ -10,6 +10,8 @@
relay-1 / relay-2 / …
```
Windows 现支持可选的 [USB ADB 模拟](docs/windows-usb.md),默认网络模式保持不变。
已部署的集群和使用方法见 [集群部署与协议](docs/cluster.md)。不配置集群时保留原有 v1 单中继模式,供兼容旧客户端;以下原有单机启动命令也仍可使用。
## 目录说明
@@ -19,6 +21,7 @@
| 目录 | 作用 | 主要语言/格式 |
| --- | --- | --- |
| `agent/` | 远程设备守护程序 ads-agent,注册设备、连接手机 ADB、建立转发并重连;源码在 `src/` | Rust、TOML |
| `usb/` | 可选 ads-usb 本机虚拟 ADB USB 设备,提供回环 USB/IP、描述符和 ADB 帧适配;Windows 使用已签名 USBip 虚拟控制器 | Rust、TOML |
| `client/` | 本地守护程序 ads-client,维护设备租约、监听本地端口并自动调用 adb connect;源码在 `src/` | Rust、TOML |
| `server/` | ads-server 控制中心、旧协议兼容转发及独立 ads-relay 中继节点 | Go |
| `server/cmd/ads-relay/` | 独立中继入口,提供短期票据认证、WSS 数据配对及可选 STUN | Go |
@@ -58,7 +61,7 @@
| `crates/ads-core/` | 共用 Rust 库 | WSS、协议、ADB smart socket、流式转发 |
| `deploy/` | 部署示例 | Caddy、systemd、launchd 示例 |
四个后端程序均为独立可执行文件;另有 Avalonia 桌面工作台,不依赖 Python 运行正式程序。两端守护程序当前作为前台长运行进程,启动安装交给各平台进程管理器;尚未实现原生 Windows Service 安装器。
四个网络后端与可选 ads-usb 均为独立可执行文件;另有 Avalonia 桌面工作台,不依赖 Python 运行正式程序。两端守护程序当前作为前台长运行进程,启动安装交给各平台进程管理器;尚未实现原生 Windows Service 安装器。
## 编译
@@ -77,7 +80,7 @@ Linux / macOS:
sh scripts/build.sh
```
产物在 `bin/`,Windows 是四个后端 `.exe`。Go 服务器和 Rust 核心使用跨平台 API;Rust 两端和桌面在 Windows x64 验证,Go 控制中心与中继已部署到 Linux amd64;其余平台仍需验证构建、进程托管和 ADB 权限。
产物在 `bin/`,Windows 是四个网络后端及一个可选 ads-usb `.exe`。Go 服务器和 Rust 核心使用跨平台 API;Rust 两端和桌面在 Windows x64 验证,Go 控制中心与中继已部署到 Linux amd64;其余平台仍需验证构建、进程托管和 ADB 权限。
## 1. 公网服务器
+2
View File
@@ -22,3 +22,5 @@ $env:ADS_CLIENT_TOKEN = '<本地端令牌>'
- `--status-file <JSON路径>`:输出当前 p2p/relay/mixed/negotiating/idle、通道数和节点 ID,供桌面展示。
节点断线会中断现有 TCP 流;本地 ADB 在重试后创建新通道,重新选择路线,不支持将原 TCP 流无缝迁移。旧中心或旧 agent 会协商回 v1 模式。
可选 `--lease-status-file <路径>` 输出 true/false,供虚拟 USB 启动器等待租约,不包含票据。USB 模式需加 `--no-auto-connect`,由 ads-usb 使用本地原始 adbd 端点,不能把 USB/IP 接到 5037。见 docs/windows-usb.md。
+15
View File
@@ -42,6 +42,9 @@ struct Args {
/// Machine-readable active transport state for desktop clients
#[arg(long)]
status_file: Option<PathBuf>,
/// Optional lease readiness file for virtual USB consumers (no secret tickets)
#[arg(long)]
lease_status_file: Option<PathBuf>,
}
#[derive(Clone)]
@@ -50,6 +53,15 @@ struct LeaseState {
protocol: u8,
}
fn publish_lease(args: &Args, ready: bool) {
if let Some(file) = &args.lease_status_file {
let temp = file.with_extension("tmp");
if std::fs::write(&temp, if ready { "true" } else { "false" }).is_ok() {
let _ = std::fs::rename(temp, file);
}
}
}
async fn lease_once(args: &Args, state: &watch::Sender<Option<LeaseState>>) -> Result<()> {
let mut ws = dial(
args.network
@@ -63,6 +75,7 @@ async fn lease_once(args: &Args, state: &watch::Sender<Option<LeaseState>>) -> R
bail!("expected leased response");
}
let id = response.lease.context("missing lease ticket")?;
publish_lease(args, true);
state.send_replace(Some(LeaseState {
id,
protocol: response.protocol,
@@ -80,6 +93,7 @@ async fn maintain_lease(args: Arc<Args>, state: watch::Sender<Option<LeaseState>
if let Err(error) = lease_once(&args, &state).await {
warn!(%error, "lease unavailable; reconnecting");
}
publish_lease(&args, false);
state.send_replace(None);
if started.elapsed() > Duration::from_secs(30) {
delay = 1;
@@ -164,6 +178,7 @@ async fn accept_connections(
async fn main() -> Result<()> {
init_logging();
let args = Arc::new(Args::parse());
publish_lease(&args, false);
validate_token(&args.token)?;
if !valid_device_id(&args.device) {
bail!("invalid device ID");
+8 -2
View File
@@ -23,7 +23,7 @@ internal static class Program
Exception? failure = null;
Dispatcher.UIThread.Post(async () =>
{
try { await RunAsync(args.Contains("--live"), args.Contains("--screen")); }
try { await RunAsync(args.Contains("--live"), args.Contains("--screen"), args.Contains("--usb")); }
catch (Exception error) { failure = error; }
finally { finished.Cancel(); }
});
@@ -47,7 +47,7 @@ internal static class Program
}
}
private static async Task RunAsync(bool live, bool screen)
private static async Task RunAsync(bool live, bool screen, bool usb)
{
var root = DesktopPaths.ProjectRoot() ?? throw new InvalidOperationException("Project root not found");
var folder = Path.Combine(root, "work", "desktop-smoke", Guid.NewGuid().ToString("N"));
@@ -55,6 +55,11 @@ internal static class Program
// Avoid collisions with the interactive application or another local ADB device.
var temporary = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
temporary.Start(); vm.Port = ((System.Net.IPEndPoint)temporary.LocalEndpoint).Port; temporary.Stop();
vm.UsbMode = usb;
if (usb) {
var usbProbe = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
usbProbe.Start(); vm.UsbPort = ((System.Net.IPEndPoint)usbProbe.LocalEndpoint).Port; usbProbe.Stop();
}
var window = new MainWindow { DataContext = vm };
window.Show();
await Task.Delay(60);
@@ -105,6 +110,7 @@ internal static class Program
await UntilAsync(() => vm.Ready && vm.Model != "—", "Device did not become ready: " + vm.Notice);
await UntilAsync(() => vm.TransportStatus.Contains("P2P") || vm.TransportStatus.Contains("中继连接"), "Transport status was not updated");
Require(window.FindControl<TextBlock>("TransportStatusText")?.Text == vm.TransportStatus, "Actual route binding failed");
if (usb) Require(vm.Endpoint?.StartsWith("ADS-") == true, "USB mode did not select the USB serial");
Console.WriteLine("PASS: two healthy nodes and actual transport shown: " + vm.TransportStatus);
Require(window.FindControl<TextBlock>("ModelText")?.Text == vm.Model, "Model UI binding failed");
Require(window.FindControl<Button>("ReconnectButton")?.IsEffectivelyEnabled == true, "Reconnect button not enabled");
@@ -13,6 +13,9 @@ public sealed class DesktopSettings
public int Port { get; set; } = 15555;
public int Size { get; set; } = 1920;
public int Fps { get; set; } = 60;
public bool UsbMode { get; set; }
public string UsbipPath { get; set; } = "";
public int UsbPort { get; set; } = 3240;
public bool RelayOnly { get; set; }
public bool Audio { get; set; }
public bool ViewOnly { get; set; }
+42 -9
View File
@@ -24,6 +24,9 @@ public partial class MainViewModel : ObservableObject, IDisposable
[ObservableProperty] private int port = 15555;
[ObservableProperty] private int maxSize = 1920;
[ObservableProperty] private int maxFps = 60;
[ObservableProperty] private bool usbMode;
[ObservableProperty] private string usbipPath = WindowsUsbSession.DefaultUsbipPath();
[ObservableProperty] private int usbPort = 3240;
[ObservableProperty] private bool relayOnly;
[ObservableProperty] private string transportStatus = "尚未建立数据通道";
[ObservableProperty] private bool audio;
@@ -55,8 +58,10 @@ public partial class MainViewModel : ObservableObject, IDisposable
public string? Endpoint => endpoint;
public string? ActiveDeviceId => activeId;
private WindowsUsbSession? usbSession;
private string? leaseFile;
private Process? client, scrcpy;
private string? endpoint, activeAdb, activeId, transportFile;
private string? endpoint, rawEndpoint, activeAdb, activeId, transportFile;
private string credentialFile = "", preferredDevice = "home-phone";
private bool monitoring, disposed, initialized;
private DateTime lastRefresh;
@@ -81,6 +86,8 @@ public partial class MainViewModel : ObservableObject, IDisposable
if (settings.Adb.Length > 0) AdbPath = settings.Adb;
if (settings.Scrcpy.Length > 0) ScrcpyPath = settings.Scrcpy;
Port = settings.Port; MaxSize = settings.Size; MaxFps = settings.Fps;
UsbMode = settings.UsbMode; UsbPort = settings.UsbPort;
if (settings.UsbipPath.Length > 0) UsbipPath = settings.UsbipPath;
RelayOnly = settings.RelayOnly; Audio = settings.Audio; ViewOnly = settings.ViewOnly;
MinimizeToTray = settings.Tray; AutoRefresh = settings.AutoRefresh;
credentialFile = settings.CredentialFile;
@@ -224,7 +231,8 @@ public partial class MainViewModel : ObservableObject, IDisposable
{
var selectedPort = Port;
if (selectedPort == 5037) throw new InvalidOperationException("不能清理 ADB 主服务端口 5037,请选择隧道端口。");
var releasedOwnConnection = HasConnection && endpoint == $"127.0.0.1:{selectedPort}";
var releasedOwnConnection = HasConnection && rawEndpoint == $"127.0.0.1:{selectedPort}";
var releasedUsb = releasedOwnConnection && usbSession != null;
if (releasedOwnConnection)
{
Log($"清理端口 {selectedPort}:先断开当前工作台管理的连接。");
@@ -238,7 +246,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
try
{
var adb = DesktopPaths.ResolveTool(AdbPath, "adb");
await AdbAsync(adb, lifetime.Token, "disconnect", $"127.0.0.1:{selectedPort}");
if (!releasedUsb) await AdbAsync(adb, lifetime.Token, "disconnect", $"127.0.0.1:{selectedPort}");
}
catch (Exception error) { Log("清除 ADB 端点:" + error.Message); }
PortCleanupStatus = releasedOwnConnection && ended == 0
@@ -265,7 +273,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
await ConnectCoreAsync(selected);
}));
private Task ConnectCoreAsync(DeviceItem device)
private async Task ConnectCoreAsync(DeviceItem device)
{
if (client != null) throw new InvalidOperationException("请先断开当前连接。");
if (device.Busy) throw new InvalidOperationException("设备已被其他客户端占用。");
@@ -281,6 +289,10 @@ public partial class MainViewModel : ObservableObject, IDisposable
throw new InvalidOperationException($"本地端口 {Port} 已被占用,请修改端口或先停止另一个连接客户端。");
}
finally { portCheck.Stop(); }
if (UsbMode) {
if (UsbPort == Port) throw new InvalidOperationException("USB/IP 端口不能与 ADB 隧道端口相同。");
WindowsUsbSession.Validate(UsbipPath, UsbPort);
}
var relay = RelayOptions.Parse(Server, Origin, Token);
var clientExecutable = DesktopPaths.ResolveTool(ClientPath, "ads-client");
var adb = DesktopPaths.ResolveTool(AdbPath, "adb");
@@ -290,9 +302,14 @@ public partial class MainViewModel : ObservableObject, IDisposable
transportFile = Path.Combine(folder, "transport-" + Guid.NewGuid().ToString("N") + ".json");
info.ArgumentList.Add("--transport"); info.ArgumentList.Add(RelayOnly ? "relay" : "auto");
info.ArgumentList.Add("--status-file"); info.ArgumentList.Add(transportFile);
if (UsbMode) {
leaseFile = Path.Combine(folder, "lease-" + Guid.NewGuid().ToString("N") + ".json");
info.ArgumentList.Add("--no-auto-connect");
info.ArgumentList.Add("--lease-status-file"); info.ArgumentList.Add(leaseFile);
}
TransportStatus = "正在协商连接路线";
client = Start(info);
endpoint = address; activeAdb = adb; activeId = device.Id; preferredDevice = device.Id;
rawEndpoint = address; endpoint = address; activeAdb = adb; activeId = device.Id; preferredDevice = device.Id;
OnPropertyChanged(nameof(Endpoint)); OnPropertyChanged(nameof(ActiveDeviceId));
HasConnection = true; Ready = false;
UpdateLocalOwnership();
@@ -301,7 +318,15 @@ public partial class MainViewModel : ObservableObject, IDisposable
Notice = "连接已启动;首次使用时请在手机上允许调试。";
Model = AndroidVersion = ApiLevel = "—";
Log($"连接 {device.Id},本地 ADB 地址 {address}。");
return Task.CompletedTask;
if (UsbMode) {
usbSession = new WindowsUsbSession(device.Id);
try {
await usbSession.StartAsync(UsbipPath, UsbPort, address, leaseFile!, Log, lifetime.Token);
endpoint = usbSession.Serial; OnPropertyChanged(nameof(Endpoint));
ActiveEndpoint = $"{device.Id} → USB ADB · {endpoint}";
Notice = "USB 模拟已挂载,等待本机 ADB 枚举;首次使用可能需要手机授权。";
} catch { await DisconnectCoreAsync(); throw; }
}
}
private void UpdateLocalOwnership()
@@ -358,6 +383,10 @@ public partial class MainViewModel : ObservableObject, IDisposable
};
} catch (IOException) { } catch (JsonException) { }
}
if (usbSession is { HasExited: true }) {
await Exclusive(DisconnectCoreAsync);
Notice = "USB 模拟进程已退出,请查看日志后重连。";
}
var current = client;
if (current != null)
{
@@ -445,14 +474,18 @@ public partial class MainViewModel : ObservableObject, IDisposable
private async Task DisconnectCoreAsync()
{
await StopScrcpyAsync();
var usb = usbSession; usbSession = null;
if (usb != null) await usb.StopAsync(Log);
var current = client; client = null;
await ProcessTools.StopAsync(current);
if (endpoint != null && activeAdb != null)
if (usb == null && endpoint != null && activeAdb != null)
try { await AdbAsync(activeAdb, CancellationToken.None, "disconnect", endpoint); }
catch (Exception error) { Log(error.Message); }
if (transportFile != null) { try { File.Delete(transportFile); } catch (IOException) { } }
if (leaseFile != null) { try { File.Delete(leaseFile); } catch (IOException) { } }
leaseFile = null;
transportFile = null; TransportStatus = "尚未建立数据通道";
endpoint = activeAdb = activeId = null;
rawEndpoint = endpoint = activeAdb = activeId = null;
HasConnection = Ready = false;
UpdateLocalOwnership();
OnPropertyChanged(nameof(Endpoint)); OnPropertyChanged(nameof(ActiveDeviceId));
@@ -520,7 +553,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
DesktopPaths.SaveSettings(settingsFile, new DesktopSettings
{
Server = Server.Trim(), Origin = Origin.Trim(), Client = ClientPath, Adb = AdbPath, Scrcpy = ScrcpyPath,
RelayOnly = RelayOnly, Port = Port, Size = MaxSize, Fps = MaxFps, Audio = Audio, ViewOnly = ViewOnly, Tray = MinimizeToTray,
UsbMode = UsbMode, UsbipPath = UsbipPath, UsbPort = UsbPort, RelayOnly = RelayOnly, Port = Port, Size = MaxSize, Fps = MaxFps, Audio = Audio, ViewOnly = ViewOnly, Tray = MinimizeToTray,
AutoRefresh = AutoRefresh, CredentialFile = credentialFile, PreferredDevice = activeId ?? SelectedDevice?.Id ?? preferredDevice
});
Notice = "配置已保存;令牌内容未写入配置。";
+9 -1
View File
@@ -41,7 +41,7 @@
<TextBlock x:Name="ConnectionStatusText" Text="{Binding Status}" Foreground="#66D9C0" FontSize="19" TextWrapping="Wrap"/>
<TextBlock x:Name="TransportStatusText" Text="{Binding TransportStatus}" Foreground="#A8B7CC" TextWrapping="Wrap"/>
<TextBlock x:Name="EndpointText" Text="{Binding ActiveEndpoint}" Classes="label" TextWrapping="Wrap"/>
<WrapPanel><Button x:Name="ConnectButton" Content="连接所选设备" Command="{Binding ConnectCommand}"/><Button x:Name="ReconnectButton" Content="重新连接" Command="{Binding ReconnectCommand}"/><Button x:Name="DisconnectButton" Content="断开连接" Command="{Binding DisconnectCommand}"/><Button Content="复制 ADB 地址" IsEnabled="{Binding HasConnection}" Click="CopyEndpointClick"/><Button x:Name="ClearPortButton" Content="清理占用端口" Command="{Binding ClearPortCommand}"/></WrapPanel>
<WrapPanel><Button x:Name="ConnectButton" Content="连接所选设备" Command="{Binding ConnectCommand}"/><Button x:Name="ReconnectButton" Content="重新连接" Command="{Binding ReconnectCommand}"/><Button x:Name="DisconnectButton" Content="断开连接" Command="{Binding DisconnectCommand}"/><Button Content="复制设备标识" IsEnabled="{Binding HasConnection}" Click="CopyEndpointClick"/><Button x:Name="ClearPortButton" Content="清理占用端口" Command="{Binding ClearPortCommand}"/></WrapPanel>
<TextBlock Text="断开连接只释放本机通道,远程手机守护程序会继续在线。" TextWrapping="Wrap" Classes="label" FontSize="12"/>
</StackPanel>
</Border>
@@ -95,6 +95,14 @@
<TextBlock Text="scrcpy 可执行文件"/><Grid ColumnDefinitions="*,Auto"><TextBox Text="{Binding ScrcpyPath}"/><Button Grid.Column="1" Content="选择" Tag="scrcpy" Click="ChooseToolClick" Margin="10,5,0,12"/></Grid>
<TextBlock Text="{Binding ToolsStatus}" Classes="label" TextWrapping="Wrap"/>
</StackPanel></Border>
<Border Classes="card"><StackPanel Spacing="10">
<TextBlock Text="可选 USB 模拟 · Windows" Classes="section"/>
<CheckBox x:Name="UsbModeCheck" Content="将远程手机挂载为本机 USB ADB 设备" IsChecked="{Binding UsbMode}"/>
<TextBlock Text="需要安装 USBip 虚拟控制器驱动。仅模拟 ADB 接口;首次使用仍需手机授权,修改在下次连接生效。" Classes="label" TextWrapping="Wrap"/>
<TextBlock Text="usbip.exe 路径"/><TextBox Text="{Binding UsbipPath}" Watermark="C:\Program Files\USBip\usbip.exe"/>
<Grid ColumnDefinitions="*,180"><TextBlock Text="本机 USB/IP 端口" VerticalAlignment="Center"/><NumericUpDown Grid.Column="1" Value="{Binding UsbPort}" Minimum="1024" Maximum="65535"/></Grid>
<TextBlock Text="驱动安装方式见项目 docs/windows-usb.md;默认网络 ADB 模式不需要此组件。" Classes="label" TextWrapping="Wrap"/>
</StackPanel></Border>
<Border Classes="card"><StackPanel Spacing="12">
<TextBlock Text="本地连接" Classes="section"/>
<CheckBox x:Name="RelayOnlyCheck" Content="仅使用中继(关闭时 P2P 优先,失败自动选择中继节点)" IsChecked="{Binding RelayOnly}"/>
+72
View File
@@ -0,0 +1,72 @@
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using Microsoft.Win32;
namespace Ads.Desktop;
/// <summary>Owns one loopback USB/IP export and its exact imported hub port.</summary>
public sealed class WindowsUsbSession
{
private Process? bridge;
private string? usbip;
private int? hubPort;
public string Serial { get; }
public bool HasExited => bridge is { HasExited: true };
public WindowsUsbSession(string device) => Serial = "ADS-" + (device.Length <= 116 ? device : Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(device)))[..24]);
public static string DefaultUsbipPath()
{
var candidate = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "USBip", "usbip.exe");
return File.Exists(candidate) ? candidate : "usbip";
}
public static void Validate(string path, int port)
{
if (!OperatingSystem.IsWindows()) throw new InvalidOperationException("USB 模拟目前仅支持 Windows。");
if (port is < 1024 or > 65535) throw new InvalidOperationException("USB/IP 端口范围为 1024–65535。");
using var service = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\usbip2_ude");
if (service == null) throw new InvalidOperationException("未安装 USBip 虚拟控制器驱动,请先使用 USB 模拟配置中的安装说明。");
DesktopPaths.ResolveTool(path, "usbip");
DesktopPaths.ResolveTool(DesktopPaths.FindTool("ads-usb"), "ads-usb");
LocalPortProcesses.EnsureAvailable(port);
}
public async Task StartAsync(string path, int port, string upstream, string leaseFile, Action<string> log, CancellationToken cancellation)
{
usbip = DesktopPaths.ResolveTool(path, "usbip");
var deadline = DateTime.UtcNow.AddSeconds(40);
while (!File.Exists(leaseFile) || (await File.ReadAllTextAsync(leaseFile, cancellation)).Trim() != "true")
{
if (DateTime.UtcNow > deadline) throw new InvalidOperationException("USB 模拟等待设备租约超时。");
await Task.Delay(150, cancellation);
}
var executable = DesktopPaths.ResolveTool(DesktopPaths.FindTool("ads-usb"), "ads-usb");
bridge = new Process { StartInfo = ProcessTools.CreateStartInfo(executable,
["--listen", $"127.0.0.1:{port}", "--upstream", upstream, "--serial", Serial]) };
bridge.OutputDataReceived += (_, e) => { if (e.Data != null) log(e.Data); };
bridge.ErrorDataReceived += (_, e) => { if (e.Data != null) log(e.Data); };
bridge.Start(); bridge.BeginOutputReadLine(); bridge.BeginErrorReadLine();
deadline = DateTime.UtcNow.AddSeconds(5);
while (true)
{
if (bridge.HasExited) throw new InvalidOperationException("虚拟 USB 设备进程退出,请检查 USB/IP 端口。");
try { using var probe = new TcpClient(); await probe.ConnectAsync(IPAddress.Loopback, port, cancellation); break; }
catch (SocketException) when (DateTime.UtcNow < deadline) { await Task.Delay(100, cancellation); }
}
var attach = await ProcessTools.RunAsync(ProcessTools.CreateStartInfo(usbip,
["--tcp-port", port.ToString(), "attach", "--remote", "127.0.0.1", "--bus-id", "1-1", "--terse", "--once"]), cancellation);
if (attach.ExitCode != 0 || !int.TryParse(attach.Output.Trim(), out var importedPort) || importedPort is < 1 or > 127)
throw new InvalidOperationException("虚拟 USB 挂载失败:" + attach.Error.Trim() + " " + attach.Output.Trim());
hubPort = importedPort;
log($"USB ADB 已挂载:{Serial},本机控制器端口 {hubPort}。");
}
public async Task StopAsync(Action<string> log)
{
// Closing our export first forces the driver to remove this device even if detach fails.
var process = bridge; bridge = null;
await ProcessTools.StopAsync(process);
hubPort = null;
// --once creates no persistent retry. TCP EOF removes only our virtual device;
// do not detach by a port number which the driver could already have reused.
log("本次虚拟 USB 设备已断开。");
}
}
+4
View File
@@ -58,3 +58,7 @@ dotnet run --project Ads.Desktop.Smoke -c Debug -- --live --screen
## 集群连接
地址指向控制中心。默认 P2P 优先,连接配置的“仅使用中继”可跳过直连;修改在下次连接生效。连接管理显示实际 P2P/中继节点,控制中心配置卡显示节点健康及通道数。节点健康约每 5 秒由中心探测,桌面刷新设备时读取。
## Windows USB 模拟
连接配置提供可选 USB 模式、usbip.exe 路径和回环 USB/IP 端口;需要已签名的 USBip UDE 控制器。启动时等待设备租约,再导入虚拟设备;监控、设备信息和 scrcpy 使用 USB 序列号。安装与限制见 [Windows USB 文档](../docs/windows-usb.md)。
+70
View File
@@ -0,0 +1,70 @@
# 可选 Windows USB 模拟
## 原理与范围
```text
本机原版 ADB / WinUSB
↕ USB 请求
已签名 USBip UDE 虚拟控制器
↕ 本机回环 USB/IP
ads-usb(本项目的虚拟 ADB USB 设备)
↕ 本机原始 adbd 流
ads-client → P2P / WSS 中继 → ads-agent → 手机 TCP adbd
```
这是 USB 枚举与端点适配,不会执行 adb connect 来冒充 USB 设备。已有远程手机仍可保持 LAN ADB 接入,远程电脑、控制中心和中继无需为此更改程序或开放 USB/IP 端口。网络 ADB 是默认模式,USB 模拟为可选开关。
本项目没有新增内核驱动,而是使用上游 [usbip-win2](https://github.com/vadimgrn/usbip-win2) 已签名的 UDE 控制器。虚拟 ADB 接口为 FF/42/01,bulk IN 0x81 / OUT 0x02,512 字节最大包,提供 Microsoft OS 1.0 的 WinUSB 兼容 ID 与 Android ADB 接口 GUID。当前兼容设备身份为 18D1:4EE7,序列号 ADS-设备ID(超长 ID 使用哈希),用于本机软件模拟,不能把它作为自有硬件 VID 分配。
只模拟 ADB,不包含 MTP、fastboot、音视频 USB 接口。P2P/中继和网络延迟仍然存在。Linux/macOS 后端未实现;当前驱动安装脚本固定支持 Windows x64。
## 安装
以 PowerShell 7 从项目根目录运行:
```powershell
# 只下载、验证,不更改系统
.\scripts\install-windows-usb.ps1
# 启动上游安装器;管理员 UAC 确认后完成安装
.\scripts\install-windows-usb.ps1 -Install
```
固定上游 USBip 0.9.8.1 x64,脚本同时核对 SHA256 和有效 Authenticode 发布者证书:
- SHA256:38CAD6D4432B52D5BB9409D9AD03B72FDFFC4ADA4CD3A48FBECA1A2752A8518A
- 发布者:Cloudyne Systems (Scheibling Consulting AB)
- 证书指纹:9AC56B6C76141395D74FFF6652818376E80B9C95
安装会短暂重启 USB 集线器;安装器可能要求随后重启 Windows。脚本不会强制重启、打开测试签名或关闭 Secure Boot。升级版本时需重新核验发布资产、签名及驱动兼容性。第三方安装包不进入 Git 或桌面分发包。
2026-11-12 已在当前 Windows 安装驱动,usbip2_ude 与 usbip2_filter 均运行。安装器报告需要重启,但未自动重启;重启前的虚拟 USB 枚举、远程 shell 已通过。
## 桌面使用
1. 构建后端和工作台(scripts/build.ps1、scripts/build-desktop.ps1)。
2. 进入“连接配置 → 可选 USB 模拟 · Windows”。勾选 USB 模拟,指定 usbip.exe(默认 C:\Program Files\USBip\usbip.exe)。
3. USB/IP 端口默认 3240,仅回环,必须与本地 ADB 隧道端口不同且未占用。
4. 连接设备。工作台先启动 ads-client 并等待设备租约,再启动虚拟设备并调用 usbip 挂载。
5. 本机 ADB 显示 ADS-home-phone,使用 `adb -s ADS-home-phone shell` 或桌面投屏。无需 adb connect。
6. 断开连接时关闭本次虚拟设备和本次网络客户端,释放远端租约,不卸载控制器驱动,不操作其他 USB 设备。
同机有其他 USB 手机时,`adb -d` 会报告 more than one USB device,这是原版 ADB 的行为;使用 -s 指定模拟设备。只连接这一个 USB ADB 设备时才能用 -d 唯一选择。
移除可选组件可通过 Windows“已安装的应用”卸载 USBip;先断开本项目 USB 模式。卸载涉及系统驱动,应遵循其卸载器提示。取消桌面开关即可继续使用网络模式。
## 协议与验证
USB/IP import/list、独占导入、设备/配置/字符串/WinUSB 描述符、端点 STALL、bulk IN/OUT、UNLINK、零长度包、断开与资源回收均在本项目实现。按 ADB 24 字节包头和载荷重建传输边界,避免把 TCP 分段误当 USB 短包;最大 ADB 载荷和单 URB 为 1 MiB,接收队列与待处理 URB 有界。USB/IP 无公网认证层,因此严格限制为回环;跨公网只走已有认证、加密的 ADS 通道。
```powershell
cargo test -p ads-usb --locked
python tests/usb_e2e.py
cd desktop
dotnet run --project Ads.Desktop.Smoke -c Debug -- --live --screen --usb
```
2026-11-12:协议集成测试通过,包含任意 TCP 分段下的 ADB 包头/载荷还原、512 字节载荷后的 ZLP、取消无多余完成包、畸形/超大 URB 拒绝。真实已签名 Windows 控制器导入后,原版 ADB 枚举 ADS-home-phone 并执行远端 echo / getprop;本机已有物理 USB 手机未被移除,adb -d 正确报告多 USB 设备。
参考:[USB/IP 协议](https://www.kernel.org/doc/html/latest/usb/usbip_protocol.html)、[Microsoft UDE](https://learn.microsoft.com/en-us/windows-hardware/drivers/usbcon/developing-windows-drivers-for-emulated-usb-host-controllers-and-devices)、[AOSP Windows USB transport](https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/client/usb_windows.cpp)。
桌面 USB 模式实测通过:P2P 路线状态、USB 序列号选择、设备型号、真实 scrcpy 视频、重新连接、断开后释放租约、清理本机隧道端口时一并移除虚拟 USB,以及凭据不写入配置/日志。结束后 USBip 控制器导入数量为 0,物理 USB 手机保持在线。
+5 -3
View File
@@ -12,9 +12,11 @@ try {
if ($LASTEXITCODE -ne 0) { throw 'Desktop publish failed' }
} finally { Pop-Location }
$suffix = if ($Runtime.StartsWith('win-')) { '.exe' } else { '' }
$client = Join-Path $projectRoot ('bin/ads-client' + $suffix)
if (Test-Path -LiteralPath $client) {
Copy-Item -LiteralPath $client -Destination (Join-Path $outputDirectory ('ads-client' + $suffix)) -Force
foreach ($toolName in @('ads-client', 'ads-usb')) {
$client = Join-Path $projectRoot ('bin/' + $toolName + $suffix)
if (Test-Path -LiteralPath $client) {
Copy-Item -LiteralPath $client -Destination (Join-Path $outputDirectory ($toolName + $suffix)) -Force
}
}
if ($Runtime.StartsWith('win-') -and (Test-Path -LiteralPath (Join-Path $projectRoot 'bin/tools/scrcpy/scrcpy.exe'))) {
$tools = Join-Path $outputDirectory 'tools/scrcpy'
+2 -2
View File
@@ -8,7 +8,7 @@ try {
else { cargo build --workspace --release --locked }
if ($LASTEXITCODE -ne 0) { throw 'Rust build failed' }
New-Item -ItemType Directory -Force -Path (Join-Path $projectRoot 'bin') | Out-Null
foreach ($name in @('ads-agent', 'ads-client')) {
foreach ($name in @('ads-agent', 'ads-client', 'ads-usb')) {
Copy-Item -LiteralPath (Join-Path $projectRoot "target/$configuration/$name.exe") -Destination (Join-Path $projectRoot "bin/$name.exe") -Force
}
Push-Location (Join-Path $projectRoot 'server')
@@ -19,4 +19,4 @@ try {
if ($LASTEXITCODE -ne 0) { throw 'Relay build failed' }
} finally { Pop-Location }
} finally { Pop-Location }
Write-Host "Built control server, relay node, agent and client in $projectRoot/bin"
Write-Host "Built control server, relay node, agent, client and optional USB bridge in $projectRoot/bin"
+1 -1
View File
@@ -4,7 +4,7 @@ project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
cd "$project_root"
cargo build --workspace --release --locked
mkdir -p bin
cp target/release/ads-agent target/release/ads-client bin/
cp target/release/ads-agent target/release/ads-client target/release/ads-usb bin/
cd server
go build -trimpath -o ../bin/ads-server .
go build -trimpath -o ../bin/ads-relay ./cmd/ads-relay
+21
View File
@@ -0,0 +1,21 @@
param([switch]$Install)
$ErrorActionPreference = 'Stop'
if (-not $IsWindows) { throw 'Windows only; run using PowerShell 7' }
if ([Runtime.InteropServices.RuntimeInformation]::OSArchitecture -ne 'X64') { throw 'This pinned installer supports Windows x64 only' }
$projectRoot = Split-Path $PSScriptRoot -Parent
$installer = Join-Path $projectRoot 'work/USBip-0.9.8.1-x64.exe'
$expectedHash = '38CAD6D4432B52D5BB9409D9AD03B72FDFFC4ADA4CD3A48FBECA1A2752A8518A'
New-Item -ItemType Directory -Force -Path (Split-Path $installer -Parent) | Out-Null
if (-not (Test-Path -LiteralPath $installer)) {
Invoke-WebRequest 'https://github.com/vadimgrn/usbip-win2/releases/download/v.0.9.8.1/USBip-0.9.8.1-x64.exe' -OutFile $installer
}
if ((Get-FileHash -LiteralPath $installer -Algorithm SHA256).Hash -ne $expectedHash) { throw 'Installer SHA256 mismatch' }
$signature = Get-AuthenticodeSignature -LiteralPath $installer
if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Thumbprint -ne '9AC56B6C76141395D74FFF6652818376E80B9C95') { throw 'Unexpected installer signature' }
Write-Output "Verified upstream USBip 0.9.8.1 installer: $installer"
if ($Install) {
# Interactive installation retains user control. Never change test signing or Secure Boot.
$process = Start-Process -FilePath $installer -ArgumentList '/NORESTART' -Verb RunAs -PassThru -Wait
if ($process.ExitCode -notin @(0,3010)) { throw "USBip installer exited with code $($process.ExitCode)" }
if ($process.ExitCode -eq 3010) { Write-Output 'Reboot required; no reboot was started.' }
}
+69
View File
@@ -0,0 +1,69 @@
"""USB/IP protocol and ADB framing integration, without installing a kernel driver."""
from e2e import *
import struct
def receive(sock,size):
result=bytearray()
while len(result)<size:
chunk=sock.recv(size-len(result))
assert chunk,"unexpected EOF"
result.extend(chunk)
return bytes(result)
def frame(payload):
command=int.from_bytes(b'CNXN','little')
return struct.pack('<6I',command,0x1000000,1024*1024,len(payload),sum(payload),command^0xffffffff)+payload
def main():
folder=ROOT/'work/usb-e2e';folder.mkdir(parents=True,exist_ok=True)
port=free_port();phone=socket.socket();phone.bind(('127.0.0.1',0));phone.listen();phone.settimeout(15)
received=[];finished=threading.Event()
def backend():
try:
sock,_=phone.accept()
with sock:
data=frame(b'A'*512)+frame(b'end')
for offset in range(0,len(data),7):sock.sendall(data[offset:offset+7])
received.append(receive(sock,8));finished.wait(15)
finally:phone.close()
threading.Thread(target=backend,daemon=True).start()
handle=open(folder/'usb.log','wb')
binary=ROOT/'target/debug'/('ads-usb.exe' if os.name=='nt' else 'ads-usb')
process=subprocess.Popen([str(binary),'--listen',f'127.0.0.1:{port}','--upstream',f'127.0.0.1:{phone.getsockname()[1]}','--serial','ADS-test'],stdout=handle,stderr=handle)
def connect():
s=socket.create_connection(('127.0.0.1',port),timeout=3);s.settimeout(4);return s
def available():
with connect():return True
def submit(s,seq,direction,ep,length,payload=b'',setup=bytes(8)):
s.sendall(struct.pack('!10I',1,seq,0x10001,direction,ep,0,length,0,0xffffffff,0)+setup+payload)
def reply(s,seq,status=0):
h=receive(s,48);command,actual_seq=struct.unpack('!2I',h[:8]);actual_status=struct.unpack('!i',h[20:24])[0];size=struct.unpack('!I',h[24:28])[0]
assert command==3 and seq==actual_seq and actual_status==status,(command,actual_seq,actual_status)
return size
try:
wait_until(available,'USB/IP startup')
with connect() as s:
s.sendall(struct.pack('!HHI',0x111,0x8005,0));data=receive(s,328)
assert data[:12]==struct.pack('!HHII',0x111,5,0,1);assert data[-4:]==bytes([255,66,1,0])
with connect() as s:
s.sendall(struct.pack('!HHI',0x111,0x8003,0)+b'1-1'+bytes(29));data=receive(s,320);assert data[:8]==struct.pack('!HHI',0x111,3,0)
with connect() as duplicate:
duplicate.sendall(struct.pack('!HHI',0x111,0x8003,0)+b'1-1'+bytes(29));assert receive(duplicate,8)[-4:]==struct.pack('!I',2)
submit(s,1,1,0,18,setup=bytes([128,6,0,1,0,0,18,0]));assert reply(s,1)==18;assert receive(s,18)[8:12]==bytes([209,24,231,78])
submit(s,2,1,0,255,setup=bytes([128,6,0,15,0,0,255,0]));assert reply(s,2,-32)==0
submit(s,3,0,2,8,b'from-usb');assert reply(s,3)==8
submit(s,4,1,1,24);assert reply(s,4)==24;assert receive(s,24)==frame(b'A'*512)[:24]
submit(s,5,1,1,512);assert reply(s,5)==512;assert receive(s,512)==b'A'*512
submit(s,6,1,1,24);assert reply(s,6)==0
submit(s,7,1,1,24);assert reply(s,7)==24;assert receive(s,24)==frame(b'end')[:24]
submit(s,8,1,1,512);assert reply(s,8)==3;assert receive(s,3)==b'end'
submit(s,9,1,1,512)
s.sendall(struct.pack('!6I',2,10,0x10001,0,0,9)+bytes(24));h=receive(s,48);assert struct.unpack('!2I',h[:8])==(4,10);assert struct.unpack('!i',h[20:24])[0]==-104
submit(s,11,1,3,1);assert reply(s,11,-32)==0
wait_until(lambda:received==[b'from-usb'],'bulk OUT delivery')
print('PASS: USB/IP list/import/exclusivity, descriptor stalls, fragmented ADB header/payload, ZLP, bulk OUT, URB unlink and invalid endpoint',flush=True)
submit(s,12,1,1,1024*1024+1);assert s.recv(1)==b''
print('PASS: oversized URB rejected',flush=True)
finally:
finished.set();process.terminate();process.wait(timeout=8);handle.close()
if __name__=='__main__':main()
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "ads-usb"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
anyhow.workspace = true
clap.workspace = true
tokio.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
+15
View File
@@ -0,0 +1,15 @@
# ads-usb:可选虚拟 ADB USB 设备
源码在 `src/`(Rust);`main.rs` 管理回环监听和会话,`descriptors.rs` 提供 ADB/WinUSB 描述符,`protocol.rs` 实现 USB/IP 1.1.1、控制请求、批量传输、URB 取消与 ADB 帧适配。依赖 USBip 虚拟控制器的 Windows 后端已验证,程序本身不包含内核驱动。
```powershell
cargo build -p ads-usb --release --locked
# 先运行 ads-client --no-auto-connect,取得远端设备租约
.\bin\ads-usb.exe --listen 127.0.0.1:3240 --upstream 127.0.0.1:15555 --serial ADS-home-phone
& 'C:\Program Files\USBip\usbip.exe' --tcp-port 3240 attach -r 127.0.0.1 -b 1-1 --terse --once
adb -s ADS-home-phone shell getprop ro.product.model
```
USB/IP 只监听回环,不能向公网发布。进程只允许一个导入者,上游直接使用本机 ads-client 的 adbd 字节流,不是 ADB server 5037。无需远程手机实际 USB 插线;远端可以仍通过 LAN adbd 接入。关闭本次 ads-usb 进程会断开本次虚拟设备。
仅提供 ADB 接口;不提供 MTP、fastboot 或整台手机 USB 透传。Windows 安装、使用和验证见 [windows-usb.md](../docs/windows-usb.md)。
+122
View File
@@ -0,0 +1,122 @@
//! One high-speed vendor-specific ADB interface, no MTP or other USB functions.
pub const BUS_ID: &str = "1-1";
pub const GUID: &str = "{F72FE0D4-CBCB-407D-8814-9ED673D0DD6B}";
pub const DEVICE: &[u8] = &[
18, 1, 0, 2, 0, 0, 0, 64, 0xd1, 0x18, 0xe7, 0x4e, 0, 1, 1, 2, 3, 1,
];
pub const CONFIG: &[u8] = &[
9, 2, 32, 0, 1, 1, 0, 0x80, 50, 9, 4, 0, 0, 2, 0xff, 0x42, 1, 0, 7, 5, 0x81, 2, 0, 2, 0, 7, 5,
0x02, 2, 0, 2, 0,
];
pub fn string(value: &str) -> Vec<u8> {
let body: Vec<u8> = value.encode_utf16().flat_map(u16::to_le_bytes).collect();
let mut out = vec![(body.len() + 2) as u8, 3];
out.extend(body);
out
}
pub fn compat_id() -> Vec<u8> {
let mut out = vec![0; 40];
out[..4].copy_from_slice(&40u32.to_le_bytes());
out[4..6].copy_from_slice(&0x100u16.to_le_bytes());
out[6..8].copy_from_slice(&4u16.to_le_bytes());
out[8] = 1;
out[17] = 1;
out[18..24].copy_from_slice(b"WINUSB");
out
}
pub fn properties() -> Vec<u8> {
let name: Vec<u8> = "DeviceInterfaceGUIDs\0"
.encode_utf16()
.flat_map(u16::to_le_bytes)
.collect();
let data: Vec<u8> = format!("{GUID}\0\0")
.encode_utf16()
.flat_map(u16::to_le_bytes)
.collect();
let section = 14 + name.len() + data.len();
let mut out = Vec::new();
out.extend(((10 + section) as u32).to_le_bytes());
out.extend(0x100u16.to_le_bytes());
out.extend(5u16.to_le_bytes());
out.extend(1u16.to_le_bytes());
out.extend((section as u32).to_le_bytes());
out.extend(7u32.to_le_bytes());
out.extend((name.len() as u16).to_le_bytes());
out.extend(name);
out.extend((data.len() as u32).to_le_bytes());
out.extend(data);
out
}
pub fn control(setup: [u8; 8], serial: &str, configured: &mut u8) -> Result<Vec<u8>, i32> {
let [kind, request, vl, vh, il, ih, ll, lh] = setup;
let value = u16::from_le_bytes([vl, vh]);
let index = u16::from_le_bytes([il, ih]);
let length = u16::from_le_bytes([ll, lh]) as usize;
let mut data = match (kind, request) {
(0x80, 6) => match (vh, vl) {
(1, 0) => DEVICE.to_vec(),
(2, 0) => CONFIG.to_vec(),
(3, 0) => vec![4, 3, 9, 4],
(3, 1) => string("TTSTD"),
(3, 2) => string("ADS Virtual ADB"),
(3, 3) => string(serial),
(3, 0xee) => {
let mut v = string("MSFT100");
v.extend([0x20, 0]);
v[0] = 18;
v
}
(6, 0) => vec![10, 6, 0, 2, 0, 0, 0, 64, 1, 0],
_ => return Err(-32),
},
(0xc0, 0x20) if index == 4 => compat_id(),
(0xc0 | 0xc1, 0x20) if index == 5 => properties(),
(0x80 | 0x81 | 0x82, 0) => vec![0, 0],
(0, 5) if value <= 127 => vec![],
(0, 9) if value <= 1 => {
*configured = value as u8;
vec![]
}
(0x80, 8) => vec![*configured],
(0x81, 10) if index == 0 => vec![0],
(1, 11) if value == 0 && index == 0 => vec![],
(2, 1) if value == 0 && (index == 0x81 || index == 2) => vec![],
_ => return Err(-32),
};
data.truncate(length);
Ok(data)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn descriptors_are_consistent() {
assert_eq!(CONFIG.len(), 32);
assert_eq!(CONFIG[20], 0x81);
assert_eq!(CONFIG[27], 2);
assert_eq!(DEVICE.len(), 18);
assert_eq!(compat_id().len(), 40);
let p = properties();
assert_eq!(
u32::from_le_bytes(p[..4].try_into().unwrap()) as usize,
p.len()
);
}
#[test]
fn control_bounds_and_stalls() {
let mut c = 0;
assert_eq!(
control([0x80, 6, 0, 1, 0, 0, 8, 0], "ADS-test", &mut c)
.unwrap()
.len(),
8
);
assert!(control([0x80, 6, 0, 15, 0, 0, 255, 0], "ADS-test", &mut c).is_err());
assert_eq!(
control([0, 9, 1, 0, 0, 0, 0, 0], "ADS-test", &mut c).unwrap(),
Vec::<u8>::new()
);
assert_eq!(c, 1);
}
}
+65
View File
@@ -0,0 +1,65 @@
mod descriptors;
mod protocol;
use anyhow::{bail, Context, Result};
use clap::Parser;
use std::{
net::SocketAddr,
sync::{atomic::AtomicBool, Arc},
};
use tokio::{net::TcpListener, task::JoinSet};
#[derive(Parser)]
#[command(
version,
about = "Local virtual ADB USB device exported to the Windows USB/IP controller"
)]
struct Args {
#[arg(long, default_value = "127.0.0.1:3240")]
listen: SocketAddr,
/// Existing ads-client raw adbd endpoint; must be loopback
#[arg(long)]
upstream: SocketAddr,
#[arg(long, default_value = "ADS-home-phone")]
serial: String,
}
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt()
.with_env_filter("ads_usb=info")
.init();
let args = Args::parse();
if !args.listen.ip().is_loopback()
|| !args.upstream.ip().is_loopback()
|| args.listen.port() == 0
|| args.upstream.port() == 0
|| args.listen == args.upstream
{
bail!("USB/IP and upstream must be distinct loopback endpoints")
}
if args.serial.is_empty()
|| args.serial.len() > 120
|| !args
.serial
.bytes()
.all(|v| v.is_ascii_alphanumeric() || b"-_.".contains(&v))
{
bail!("serial must use ASCII letters, digits, -, _ or . (1-120 bytes)")
}
let listener = TcpListener::bind(args.listen)
.await
.context("cannot bind private USB/IP endpoint")?;
let occupied = Arc::new(AtomicBool::new(false));
let mut tasks = JoinSet::new();
tracing::info!(endpoint=%args.listen,serial=%args.serial,"virtual ADB USB device ready");
loop {
tokio::select! {
incoming=listener.accept()=>{
let (socket,_)=incoming?;if tasks.len()>=16{drop(socket);continue}
let serial=args.serial.clone();let occupied=occupied.clone();let target=args.upstream;
tasks.spawn(async move{if let Err(error)=protocol::serve(socket,target,serial,occupied).await{tracing::warn!(%error,"USB session ended");}});
},
_=tasks.join_next(),if !tasks.is_empty()=>{},
_=tokio::signal::ctrl_c()=>return Ok(()),
}
}
}
+242
View File
@@ -0,0 +1,242 @@
use crate::descriptors;
use anyhow::{bail, Context, Result};
use std::{
collections::VecDeque,
net::SocketAddr,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::Duration,
};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::{
tcp::{OwnedReadHalf, OwnedWriteHalf},
TcpStream,
},
sync::mpsc,
task::JoinSet,
time::timeout,
};
const MAX: usize = 1024 * 1024;
const IO: Duration = Duration::from_secs(30);
const DEV: u32 = 0x10001;
fn be(data: &[u8], offset: usize) -> u32 {
u32::from_be_bytes(data[offset..offset + 4].try_into().unwrap())
}
fn device() -> Vec<u8> {
let mut v = vec![0; 312];
let path = b"/ads/virtual/1-1";
v[..path.len()].copy_from_slice(path);
v[256..259].copy_from_slice(descriptors::BUS_ID.as_bytes());
for (offset, value) in [(288, 1u32), (292, 1), (296, 3)] {
v[offset..offset + 4].copy_from_slice(&value.to_be_bytes());
}
v[300..302].copy_from_slice(&0x18d1u16.to_be_bytes());
v[302..304].copy_from_slice(&0x4ee7u16.to_be_bytes());
v[304..306].copy_from_slice(&0x100u16.to_be_bytes());
v[309..312].copy_from_slice(&[1, 1, 1]);
v
}
async fn op(socket: &mut TcpStream, code: u16, status: u32) -> Result<()> {
let mut header = vec![];
header.extend(0x111u16.to_be_bytes());
header.extend(code.to_be_bytes());
header.extend(status.to_be_bytes());
timeout(IO, socket.write_all(&header)).await??;
Ok(())
}
struct Occupied(Arc<AtomicBool>);
impl Drop for Occupied {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
pub async fn serve(
mut socket: TcpStream,
target: SocketAddr,
serial: String,
occupied: Arc<AtomicBool>,
) -> Result<()> {
socket.set_nodelay(true)?;
let mut header = [0; 8];
timeout(Duration::from_secs(5), socket.read_exact(&mut header)).await??;
if header[..2] != [1, 0x11] || be(&header, 4) != 0 {
bail!("invalid USB/IP handshake")
}
match u16::from_be_bytes([header[2], header[3]]) {
0x8005 => {
op(&mut socket, 5, 0).await?;
socket.write_all(&1u32.to_be_bytes()).await?;
socket.write_all(&device()).await?;
socket.write_all(&[0xff, 0x42, 1, 0]).await?;
Ok(())
}
0x8003 => {
let mut bus = [0; 32];
timeout(Duration::from_secs(5), socket.read_exact(&mut bus)).await??;
let mut expected = [0; 32];
expected[..3].copy_from_slice(descriptors::BUS_ID.as_bytes());
if bus != expected {
op(&mut socket, 3, 1).await?;
bail!("unknown USB bus ID")
}
if occupied
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_err()
{
op(&mut socket, 3, 2).await?;
bail!("virtual USB device already imported")
}
let _guard = Occupied(occupied);
op(&mut socket, 3, 0).await?;
socket.write_all(&device()).await?;
imported(socket, target, &serial).await
}
_ => bail!("unsupported USB/IP operation"),
}
}
struct Request {
header: [u8; 48],
data: Vec<u8>,
}
async fn read_requests(mut read: OwnedReadHalf, tx: mpsc::Sender<Request>) -> Result<()> {
loop {
let mut header = [0; 48];
read.read_exact(&mut header).await?;
let command = be(&header, 0);
if command != 1 && command != 2 {
bail!("invalid USB/IP command")
}
let direction = be(&header, 12);
let size = be(&header, 24) as usize;
if command == 1 && (size > MAX || direction > 1 || !matches!(be(&header, 32), 0 | u32::MAX))
{
bail!("invalid or oversized URB")
}
let mut data = vec![
0;
if command == 1 && direction == 0 {
size
} else {
0
}
];
if !data.is_empty() {
timeout(IO, read.read_exact(&mut data)).await??;
}
tx.send(Request { header, data })
.await
.context("USB request queue closed")?;
}
}
// Preserve ADB USB transfer boundaries independently of TCP segmentation.
async fn read_adb(mut read: OwnedReadHalf, tx: mpsc::Sender<Vec<u8>>) -> Result<()> {
loop {
let mut header = vec![0; 24];
read.read_exact(&mut header).await?;
let word = |n| u32::from_le_bytes(header[n..n + 4].try_into().unwrap());
if word(0) ^ word(20) != u32::MAX {
bail!("invalid ADB frame magic")
}
let size = word(12) as usize;
if size > MAX {
bail!("ADB payload exceeds 1 MiB")
}
tx.send(header).await.context("ADB receive queue closed")?;
if size > 0 {
let mut payload = vec![0; size];
timeout(IO, read.read_exact(&mut payload)).await??;
tx.send(payload).await.context("ADB receive queue closed")?;
if size % 512 == 0 {
tx.send(vec![]).await.context("ADB receive queue closed")?;
}
}
}
}
async fn reply(
write: &mut OwnedWriteHalf,
request: &Request,
status: i32,
data: &[u8],
actual: usize,
) -> Result<()> {
let mut header = [0; 48];
header[..4].copy_from_slice(&3u32.to_be_bytes());
header[4..8].copy_from_slice(&request.header[4..8]);
header[20..24].copy_from_slice(&status.to_be_bytes());
header[24..28].copy_from_slice(&(actual as u32).to_be_bytes());
timeout(IO, async {
write.write_all(&header).await?;
write.write_all(data).await
})
.await??;
Ok(())
}
async fn unlink(write: &mut OwnedWriteHalf, request: &Request, status: i32) -> Result<()> {
let mut header = [0; 48];
header[..4].copy_from_slice(&4u32.to_be_bytes());
header[4..8].copy_from_slice(&request.header[4..8]);
header[20..24].copy_from_slice(&status.to_be_bytes());
timeout(IO, write.write_all(&header)).await??;
Ok(())
}
async fn imported(socket: TcpStream, target: SocketAddr, serial: &str) -> Result<()> {
let (read, mut write) = socket.into_split();
let (tx, mut requests) = mpsc::channel(32);
let mut tasks = JoinSet::new();
tasks.spawn(read_requests(read, tx));
let (data_tx, mut data_rx) = mpsc::channel(16);
let mut backend: Option<OwnedWriteHalf> = None;
let mut pending: VecDeque<Request> = VecDeque::new();
let mut bytes: VecDeque<Vec<u8>> = VecDeque::new();
let mut offset = 0;
let mut configured = 0;
loop {
while !pending.is_empty() && !bytes.is_empty() {
let request = pending.pop_front().unwrap();
let front = bytes.front().unwrap();
let size = (be(&request.header, 24) as usize).min(front.len() - offset);
reply(&mut write, &request, 0, &front[offset..offset + size], size).await?;
offset += size;
if offset == front.len() {
bytes.pop_front();
offset = 0;
}
}
tokio::select! {
request=requests.recv()=>{
let request=request.context("USB/IP disconnected")?;let h=&request.header;
if be(h,0)==2{
let seq=be(h,20);let found=pending.iter().position(|r|be(&r.header,4)==seq);
if let Some(index)=found{pending.remove(index);}
unlink(&mut write,&request,if found.is_some(){-104}else{0}).await?;continue
}
if be(h,8)!=DEV{bail!("incorrect device ID")}
if pending.iter().any(|r|be(&r.header,4)==be(h,4)){bail!("duplicate pending sequence")}
let direction=be(h,12);let ep=be(h,16);let size=be(h,24) as usize;
if ep==0{
let result=descriptors::control(h[40..48].try_into().unwrap(),serial,&mut configured);
match result{Ok(data)=>{let data=&data[..data.len().min(size)];reply(&mut write,&request,0,if direction==1{data}else{&[]},if direction==1{data.len()}else{request.data.len()}).await?;},Err(status)=>reply(&mut write,&request,status,&[],0).await?}
}else if (ep==1&&direction==1)||(ep==2&&direction==0){
if size==0{reply(&mut write,&request,0,&[],0).await?;continue}
if backend.is_none(){
let socket=timeout(Duration::from_secs(10),TcpStream::connect(target)).await??;socket.set_nodelay(true)?;
let(read,write)=socket.into_split();backend=Some(write);
tasks.spawn(read_adb(read,data_tx.clone()));
}
if direction==0{
timeout(IO,backend.as_mut().unwrap().write_all(&request.data)).await??;
reply(&mut write,&request,0,&[],request.data.len()).await?;
}else{
if pending.len()>=64{bail!("too many pending bulk reads")}
pending.push_back(request);
}
}else{reply(&mut write,&request,-32,&[],0).await?;}
},
data=data_rx.recv(),if bytes.len()<16=>{bytes.push_back(data.context("ADB disconnected")?);},
result=tasks.join_next()=>{return result.context("USB worker missing")?.context("USB worker failed")?;},
}
}
}