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 WindowsUsbSession : IDisposable { 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 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 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 设备已断开。"); } }