Add targeted local port cleanup to desktop workbench

This commit is contained in:
tongtong committed 2026-11-12 15:46:15 +08:00
1 parent 51c4f86918
commit ab9cc8d0a5
8 files changed
+312 -1

No files matched your search

+29
View File
@@ -9,6 +9,15 @@ internal static class Program
[STAThread]
public static int Main(string[] args)
{
if (args.Length == 2 && args[0] == "--port-child")
{
var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, int.Parse(args[1]));
listener.Start();
Console.WriteLine("READY");
Console.Out.Flush();
Thread.Sleep(Timeout.Infinite);
return 0;
}
AppBuilder.Configure<App>().UseSkia().UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false }).SetupWithoutStarting();
using var finished = new CancellationTokenSource();
Exception? failure = null;
@@ -72,6 +81,17 @@ internal static class Program
Require(!vm.HasConnection && vm.Notice.Contains("已被占用"), "Occupied port was not rejected safely");
}
finally { occupied.Stop(); }
var childInfo = ProcessTools.CreateStartInfo("dotnet", [typeof(Program).Assembly.Location, "--port-child", vm.Port.ToString()]);
using var child = System.Diagnostics.Process.Start(childInfo)!;
try
{
Require(await child.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(10)) == "READY", "Listener child did not start");
await vm.ClearPortCommand.ExecuteAsync(null);
Require(child.HasExited && vm.PortCleanupStatus.Contains("已释放"), "GUI clear-port action did not terminate listener");
Require(window.FindControl<Button>("ClearPortButton") != null, "Clear-port button is missing");
Console.WriteLine("PASS: GUI cleanup terminates the exact port owner and frees the port");
}
finally { if (!child.HasExited) { child.Kill(); child.WaitForExit(5000); } }
Console.WriteLine("PASS: Avalonia bindings and device action availability");
return;
}
@@ -118,6 +138,15 @@ internal static class Program
await vm.RefreshCommand.ExecuteAsync(null);
Require(vm.Devices.Single(d => d.Id == "home-phone").Busy == false, "Device lease was not released");
Console.WriteLine("PASS: GUI disconnect releases lease; remote gateway remains online");
vm.SelectedDevice = vm.Devices.Single(d => d.Id == "home-phone");
await vm.ConnectCommand.ExecuteAsync(null);
await UntilAsync(() => vm.Ready, "Device did not recover before own-port cleanup");
await vm.ClearPortCommand.ExecuteAsync(null);
Require(!vm.HasConnection && !vm.Ready && vm.PortCleanupStatus.Contains("已释放"), "Own connection was not cleared");
await vm.RefreshCommand.ExecuteAsync(null);
Require(!vm.Devices.Single(d => d.Id == "home-phone").Busy, "Own-port cleanup did not release lease");
Console.WriteLine("PASS: cleanup of the workbench's own port releases ADB and device lease");
vm.SaveCommand.Execute(null);
Require(!File.ReadAllText(Path.Combine(folder, "settings.json")).Contains(vm.Token), "Saved settings leaked the token");
Require(!vm.Logs.Any(line => line.Contains(vm.Token)), "UI log leaked token");
@@ -9,5 +9,6 @@
<PackageReference Include="xunit" Version="2.9.3"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2"><PrivateAssets>all</PrivateAssets></PackageReference>
<ProjectReference Include="../Ads.Desktop/Ads.Desktop.csproj"/>
<ProjectReference Include="../Ads.Desktop.Smoke/Ads.Desktop.Smoke.csproj" ReferenceOutputAssembly="false"/>
</ItemGroup>
</Project>
@@ -0,0 +1,86 @@
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using Ads.Desktop;
using Xunit;
namespace Ads.Desktop.Tests;
public class PortCleanupTests
{
private static int FreePort()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
try { return ((IPEndPoint)listener.LocalEndpoint).Port; }
finally { listener.Stop(); }
}
private static async Task<Process> ChildAsync(int port)
{
var configuration = new DirectoryInfo(AppContext.BaseDirectory).Parent!.Name;
var assembly = Path.Combine(DesktopPaths.ProjectRoot()!, "desktop", "Ads.Desktop.Smoke", "bin", configuration, "net8.0", "Ads.Desktop.Smoke.dll");
var info = ProcessTools.CreateStartInfo("dotnet", [assembly, "--port-child", port.ToString()]);
var child = Process.Start(info)!;
try
{
var ready = await child.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(10));
Assert.Equal("READY", ready);
return child;
}
catch { Stop(child); throw; }
}
private static void Stop(Process process)
{
if (!process.HasExited) { process.Kill(); process.WaitForExit(5000); }
process.Dispose();
}
[Fact]
public async Task CleanupTerminatesOnlyTheListenerAndReleasesItsPort()
{
if (!OperatingSystem.IsWindows()) return;
var targetPort = FreePort();
var otherPort = FreePort();
while (otherPort == targetPort) otherPort = FreePort();
var target = await ChildAsync(targetPort);
Process? unrelated = null;
try
{
unrelated = await ChildAsync(otherPort);
var owners = LocalPortProcesses.Inspect(targetPort);
Assert.Single(owners);
Assert.Equal(target.Id, owners[0].Id);
Assert.Equal(1, await LocalPortProcesses.TerminateAsync(targetPort, owners));
Assert.True(target.HasExited);
Assert.False(unrelated.HasExited);
Assert.Empty(LocalPortProcesses.Inspect(targetPort));
var probe = new TcpListener(IPAddress.Loopback, targetPort);
probe.Start(); probe.Stop();
}
finally { Stop(target); if (unrelated != null) Stop(unrelated); }
}
[Fact]
public async Task ChangedProcessIdentityIsNotTerminated()
{
if (!OperatingSystem.IsWindows()) return;
var port = FreePort();
var child = await ChildAsync(port);
try
{
var owner = Assert.Single(LocalPortProcesses.Inspect(port));
await Assert.ThrowsAsync<InvalidOperationException>(() => LocalPortProcesses.TerminateAsync(port, [owner with { StartedUtcTicks = owner.StartedUtcTicks + 1 }]));
Assert.False(child.HasExited);
}
finally { Stop(child); }
}
[Fact]
public async Task DoesNotTerminateCurrentWorkbenchOrAdbMainService()
{
await Assert.ThrowsAsync<InvalidOperationException>(() => LocalPortProcesses.TerminateAsync(5037, []));
await Assert.ThrowsAsync<InvalidOperationException>(() => LocalPortProcesses.TerminateAsync(15555, [new PortProcess(Environment.ProcessId, "self", 0)]));
}
}
+152
View File
@@ -0,0 +1,152 @@
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Ads.Desktop;
public sealed record PortProcess(int Id, string Name, long StartedUtcTicks);
public static class LocalPortProcesses
{
public static void EnsureAvailable(int port)
{
ValidatePort(port);
var probe = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, port);
try { probe.Server.ExclusiveAddressUse = true; probe.Start(); }
catch (System.Net.Sockets.SocketException)
{ throw new InvalidOperationException($"本地端口 {port} 仍不可用,可能被自动重启的程序占用或受系统限制。"); }
finally { probe.Stop(); }
}
public static IReadOnlyList<PortProcess> Inspect(int port)
{
ValidatePort(port);
var result = new List<PortProcess>();
foreach (var id in ListenerIds(port))
{
try
{
using var process = Process.GetProcessById(id);
result.Add(new PortProcess(id, process.ProcessName, process.StartTime.ToUniversalTime().Ticks));
}
catch (ArgumentException) { /* Listener exited during inspection. */ }
catch (Win32Exception)
{
throw new InvalidOperationException($"无法读取端口 {port} 的进程 PID {id},请检查账户权限。");
}
}
return result;
}
public static async Task<int> TerminateAsync(int port, IReadOnlyList<PortProcess> inspected, CancellationToken cancellation = default)
{
ValidatePort(port);
if (port == 5037) throw new InvalidOperationException("5037 是 ADB 主服务端口,请选择隧道端口,避免中断其他设备。");
var ended = 0;
foreach (var owner in inspected)
{
cancellation.ThrowIfCancellationRequested();
if (owner.Id <= 4 || owner.Id == Environment.ProcessId)
throw new InvalidOperationException($"端口由系统或当前工作台进程占用,不能一键结束 PID {owner.Id}。");
// Re-check both port ownership and process creation time immediately
// before termination. Never kill by process name or a stale PID alone.
if (!ListenerIds(port).Contains(owner.Id)) continue;
try
{
using var process = Process.GetProcessById(owner.Id);
if (process.StartTime.ToUniversalTime().Ticks != owner.StartedUtcTicks)
throw new InvalidOperationException("进程身份已变化,请重新检查端口后再清理。");
if (process.HasExited) continue;
process.Kill(entireProcessTree: false);
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
timeout.CancelAfter(TimeSpan.FromSeconds(5));
await process.WaitForExitAsync(timeout.Token);
ended++;
}
catch (ArgumentException) { }
catch (Win32Exception)
{
throw new InvalidOperationException($"无法结束 {owner.Name}(PID {owner.Id}),请检查权限或用管理员身份运行工作台。");
}
}
await WaitUntilAvailableAsync(port, cancellation);
return ended;
}
public static async Task WaitUntilAvailableAsync(int port, CancellationToken cancellation = default)
{
for (var attempt = 0; attempt < 50; attempt++)
{
cancellation.ThrowIfCancellationRequested();
if (ListenerIds(port).Count == 0)
try { EnsureAvailable(port); return; } catch (InvalidOperationException) { }
await Task.Delay(100, cancellation);
}
throw new InvalidOperationException($"端口 {port} 仍不可用,或占用程序已自动重启,请重新检查。");
}
private static void ValidatePort(int port)
{
if (port is < 1024 or > 65535) throw new InvalidOperationException("请选择 1024–65535 范围内的本地端口。");
}
private static HashSet<int> ListenerIds(int port)
{
if (OperatingSystem.IsWindows())
{
var ids = WindowsListenerIds(port, 2, 24, 8, 20);
ids.UnionWith(WindowsListenerIds(port, 23, 56, 20, 52));
return ids;
}
// macOS provides lsof; Linux can use the same interface when installed.
var info = new ProcessStartInfo("lsof") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true };
foreach (var argument in new[] { "-nP", $"-iTCP:{port}", "-sTCP:LISTEN", "-t" }) info.ArgumentList.Add(argument);
try
{
using var process = Process.Start(info) ?? throw new InvalidOperationException("无法启动 lsof。");
var stdout = process.StandardOutput.ReadToEndAsync();
var stderr = process.StandardError.ReadToEndAsync();
if (!process.WaitForExit(5000)) { process.Kill(); throw new InvalidOperationException("检查端口超时。"); }
var output = stdout.GetAwaiter().GetResult();
var error = stderr.GetAwaiter().GetResult();
if (process.ExitCode != 0 && (process.ExitCode != 1 || error.Length > 0))
throw new InvalidOperationException("lsof 无法检查端口:" + error.Trim());
return output.Split('\n', StringSplitOptions.RemoveEmptyEntries).Select(line => int.TryParse(line.Trim(), out var id) ? id : -1).Where(id => id > 0).ToHashSet();
}
catch (Win32Exception) { throw new InvalidOperationException("此平台检查端口需要 lsof,请先安装后重试。"); }
}
private static HashSet<int> WindowsListenerIds(int port, int family, int rowSize, int portOffset, int pidOffset)
{
var result = new HashSet<int>();
for (var attempt = 0; attempt < 3; attempt++)
{
var size = 0;
var status = GetExtendedTcpTable(IntPtr.Zero, ref size, true, family, 3, 0);
if (status == 0 && size == 0) return result;
if (status != 122 && status != 0) throw new Win32Exception((int)status);
var table = Marshal.AllocHGlobal(size);
try
{
status = GetExtendedTcpTable(table, ref size, true, family, 3, 0);
if (status == 122) continue;
if (status != 0) throw new Win32Exception((int)status);
var count = Marshal.ReadInt32(table);
if (count < 0 || size < 4 || count > (size - 4) / rowSize) throw new InvalidOperationException("系统端口表格式无效。");
for (var index = 0; index < count; index++)
{
var row = IntPtr.Add(table, 4 + index * rowSize);
var networkPort = (uint)Marshal.ReadInt32(row, portOffset);
var localPort = (int)(((networkPort & 0xff) << 8) | ((networkPort >> 8) & 0xff));
if (localPort == port) result.Add(Marshal.ReadInt32(row, pidOffset));
}
return result;
}
finally { Marshal.FreeHGlobal(table); }
}
throw new InvalidOperationException("系统端口表正在变化,请重试。");
}
[DllImport("iphlpapi.dll", SetLastError = true)]
private static extern uint GetExtendedTcpTable(IntPtr table, ref int size, [MarshalAs(UnmanagedType.Bool)] bool ordered, int family, int tableClass, uint reserved);
}
+34
View File
@@ -35,6 +35,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
[ObservableProperty] private string relayStatus = "中继尚未检测";
[ObservableProperty] private string credentialSource = "未加载客户端凭据";
[ObservableProperty] private string toolsStatus = "请检查工具路径";
[ObservableProperty] private string portCleanupStatus = "清理会结束所选本地端口的监听进程。";
[ObservableProperty] private string model = "—";
[ObservableProperty] private string androidVersion = "—";
[ObservableProperty] private string apiLevel = "—";
@@ -115,6 +116,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
ConnectCommand.NotifyCanExecuteChanged(); DisconnectCommand.NotifyCanExecuteChanged();
ReconnectCommand.NotifyCanExecuteChanged(); ReadDeviceInfoCommand.NotifyCanExecuteChanged();
StartScrcpyCommand.NotifyCanExecuteChanged(); StopScrcpyCommand.NotifyCanExecuteChanged();
ClearPortCommand.NotifyCanExecuteChanged();
}
private string Redact(string text)
@@ -203,6 +205,38 @@ public partial class MainViewModel : ObservableObject, IDisposable
private bool CanReadDeviceInfo() => !IsWorking && Ready;
private bool CanStartScrcpy() => !IsWorking && Ready && !ScreenRunning;
private bool CanStopScrcpy() => ScreenRunning;
private bool CanClearPort() => !IsWorking;
[RelayCommand(CanExecute = nameof(CanClearPort))]
private Task ClearPortAsync() => Guard(() => Exclusive(async () =>
{
var selectedPort = Port;
if (selectedPort == 5037) throw new InvalidOperationException("不能清理 ADB 主服务端口 5037,请选择隧道端口。");
var releasedOwnConnection = HasConnection && endpoint == $"127.0.0.1:{selectedPort}";
if (releasedOwnConnection)
{
Log($"清理端口 {selectedPort}:先断开当前工作台管理的连接。");
await DisconnectCoreAsync();
}
var owners = await Task.Run(() => LocalPortProcesses.Inspect(selectedPort), lifetime.Token);
PortCleanupStatus = owners.Count == 0 ? $"端口 {selectedPort} 没有监听进程。" :
string.Join(";", owners.Select(owner => $"{owner.Name} · PID {owner.Id} · 端口 {selectedPort}"));
foreach (var owner in owners) Log($"清理端口 {selectedPort}:{owner.Name}(PID {owner.Id})。");
var ended = await LocalPortProcesses.TerminateAsync(selectedPort, owners, lifetime.Token);
try
{
var adb = DesktopPaths.ResolveTool(AdbPath, "adb");
await AdbAsync(adb, lifetime.Token, "disconnect", $"127.0.0.1:{selectedPort}");
}
catch (Exception error) { Log("清除 ADB 端点:" + error.Message); }
PortCleanupStatus = releasedOwnConnection && ended == 0
? $"本机连接已断开,端口 {selectedPort} 已释放。"
: $"端口 {selectedPort} 已释放,结束了 {ended} 个占用进程。";
Notice = PortCleanupStatus + " 现在可以重新连接设备。";
Log(PortCleanupStatus);
if (Token.Length >= 32)
try { await RefreshDevicesAsync(announce: false); } catch (Exception error) { Log(error.Message); }
}));
private async Task Exclusive(Func<Task> action)
{
+2 -1
View File
@@ -40,7 +40,7 @@
<TextBlock Text="连接管理" Classes="section"/>
<TextBlock x:Name="ConnectionStatusText" Text="{Binding Status}" Foreground="#66D9C0" FontSize="19" 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"/></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="复制 ADB 地址" IsEnabled="{Binding HasConnection}" Click="CopyEndpointClick"/><Button x:Name="ClearPortButton" Content="清理占用端口" Command="{Binding ClearPortCommand}"/></WrapPanel>
<TextBlock Text="断开连接只释放本机通道,远程手机守护程序会继续在线。" TextWrapping="Wrap" Classes="label" FontSize="12"/>
</StackPanel>
</Border>
@@ -96,6 +96,7 @@
<Border Classes="card"><StackPanel Spacing="12">
<TextBlock Text="本地连接" Classes="section"/>
<Grid ColumnDefinitions="*,180"><TextBlock Text="本地 ADB 端口" VerticalAlignment="Center"/><NumericUpDown Grid.Column="1" Value="{Binding Port}" Minimum="1024" Maximum="65535"/></Grid>
<WrapPanel><Button Content="清理占用端口" Command="{Binding ClearPortCommand}" ToolTip.Tip="结束当前所选端口的监听进程"/><TextBlock Text="{Binding PortCleanupStatus}" Classes="label" TextWrapping="Wrap" MaxWidth="580" VerticalAlignment="Center"/></WrapPanel>
<CheckBox Content="关闭窗口时保留连接并最小化到托盘" IsChecked="{Binding MinimizeToTray}"/>
<TextBlock Text="配置修改在下一次连接生效。完全退出工作台会停止本机连接;远程守护程序继续运行。" TextWrapping="Wrap" Classes="label"/>
<Button Content="保存配置" Command="{Binding SaveCommand}" HorizontalAlignment="Left"/>
+1
View File
@@ -16,6 +16,7 @@ dotnet run --project Ads.Desktop -c Release
2. 自动读取 `ADS_CLIENT_TOKEN` 环境变量,或项目 `config/private/client.env`,也支持应用旁的 `client.env`。也可在“连接配置”导入文件;拒绝仅有 agent 角色令牌的文件。发布包不包含令牌。
3. 自动查找 ads-client、ADB 和 scrcpy。Windows 分发包附带 ads-client 和完整 scrcpy 官方运行目录(包含 ADB);也可选择自己的工具路径,并使用“检查工具”。仓库 `adb/`、`scrcpy/` 是源码,不能作为可执行文件使用。
4. 自动每 10 秒刷新在线设备,状态每 3 秒从本机 ADB 检查。支持连接、断开、重新连接、读取型号/Android/API 等级、复制本地 ADB 地址。当前占用标记区分“本机正在使用”和其他客户端占用。
本地端口被占用时,可点击“清理占用端口”。它会记录进程名和 PID,结束所选端口的监听进程,并验证端口已释放;本工作台当前连接优先正常断开。不会按进程名批量结束,不结束无关端口进程,也不允许一键结束系统/工作台自身或清理 ADB 主服务端口 5037。权限不足时会显示具体原因;Linux/macOS 需要 lsof,尚未在对应平台验收。
5. 手机允许调试后,点击“打开手机控制”。scrcpy 使用独立窗口,支持鼠标、键盘操作;可设置分辨率、帧率、音频与只读模式。强制 `--force-adb-forward`,避免反向连接无法穿过中继。
6. 关闭窗口默认进入托盘,右键托盘可重新打开、断开连接或退出。取消托盘选项后关闭窗口会退出。退出会停止本应用启动的 scrcpy、ads-client,并只断开所用 ADB 端点;远程守护程序继续运行。