using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using Microsoft.Win32;
namespace Ads.Desktop;
/// Owns one loopback USB/IP export and its exact imported hub port.
public sealed class UsbSession : IDisposable
{
private Process? bridge;
private string? usbip;
private int? hubPort;
public string Serial { get; }
public bool HasExited => bridge is { HasExited: true };
public UsbSession(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()
{
if(OperatingSystem.IsLinux())return DesktopPaths.FindTool("usbip");
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.IsLinux()) {
if(port is <1024 or >65535)throw new InvalidOperationException("USB/IP 端口范围为 1024–65535。");
DesktopPaths.ResolveTool(path,"usbip");DesktopPaths.ResolveTool(DesktopPaths.FindTool("pkexec"),"pkexec");
DesktopPaths.ResolveTool(DesktopPaths.FindTool("ads-usb"),"ads-usb");LocalPortProcesses.EnsureAvailable(port);return;
}
if (!OperatingSystem.IsWindows()) throw new InvalidOperationException("USB 模拟目前支持 Windows 与 Linux。");
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 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); }
}
if(OperatingSystem.IsLinux()) {
if(!Directory.Exists("/sys/module/vhci_hcd")) {
var modprobe=new[]{"/usr/sbin/modprobe","/sbin/modprobe"}.FirstOrDefault(File.Exists) ?? throw new InvalidOperationException("未安装 modprobe。");
var loaded=await ElevatedAsync(new[]{modprobe,"vhci_hcd"},cancellation);
if(loaded.ExitCode!=0)throw new InvalidOperationException("vhci_hcd 加载失败:"+loaded.Error);
}
log("请求 Linux 系统挂载授权,请确认桌面授权对话框。");
var attached=await ElevatedAsync(new[]{usbip!,"--tcp-port",port.ToString(),"attach","--remote","127.0.0.1","--busid","1-1"},cancellation);
if(attached.ExitCode!=0)throw new InvalidOperationException("Linux USB 挂载失败:"+attached.Error+attached.Output);
log($"Linux USB 已挂载:{Serial}。");return;
}
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}。");
}
private static async Task ElevatedAsync(IEnumerable args,CancellationToken cancellation) {
using var process=Process.Start(ProcessTools.CreateStartInfo(DesktopPaths.ResolveTool(DesktopPaths.FindTool("pkexec"),"pkexec"),args)) ?? throw new InvalidOperationException("无法请求系统授权。");
var output=process.StandardOutput.ReadToEndAsync();var error=process.StandardError.ReadToEndAsync();
try{await process.WaitForExitAsync(cancellation).WaitAsync(TimeSpan.FromMinutes(2),cancellation);}
catch{if(!process.HasExited)process.Kill(entireProcessTree:true);throw;}
return new ProcessResult(process.ExitCode,await output,await error);
}
public void Dispose()
{
var current = bridge; bridge = null;
try { if (current != null && !current.HasExited) current.Kill(entireProcessTree: true); } catch { }
current?.Dispose(); hubPort = null;
}
public async Task StopAsync(Action 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 设备已断开。");
}
}